为什么以下代码无法编译?如何创建一个泛型方法,根据泛型类型是"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);
}
}
Run Code Online (Sandbox Code Playgroud)