【发布时间】:2014-06-08 17:46:22
【问题描述】:
为什么下面的代码不能编译? 如果泛型类型是“int”、“bool”、“char”等,我如何创建一个调用适当的“BitConverter.GetBytes”重载的泛型方法? 更一般地,如何创建一个基于泛型参数类型调用非泛型方法的泛型方法?
using System;
public class Test
{
public static void Main()
{
var f = new Foo();
f.GetBytes(10); // should call BitConverter.GetBytes(int);
f.GetBytes(true); // should call BitConverter.GetBytes(bool);
f.GetBytes('A'); // should call BitConverter.GetBytes(char);
}
}
public class Foo
{
public byte[] GetBytes <TSource> (TSource input)
{
BitConverter.GetBytes(input);
}
}
【问题讨论】:
-
下面的答案回答了我的问题;在保持编译时类型安全且不会导致运行时性能损失的情况下,这实际上是不可能的。所以,我只是为我的方法应该接受的输入类型创建自己的重载 GetBytes 方法,然后做一些工作,最后调用适当的 BitConverter.GetBytes。