为什么下面的代码不能编译? 如何根据泛型类型是int,bool,char等创建一个泛型方法来调用相应的BitConverter.GetBytes重载? 更一般地说,我怎样才能创建一个通用的方法来调用基于泛型参数类型的非泛型方法?
使用系统; public class Test { public static void Main() { var f = new Foo(); f.GetBytes(10); //应该调用BitConverter.GetBytes(int); f.GetBytes(true); //应该调用BitConverter.GetBytes(bool); f.GetBytes('A'); //应该调用BitConverter.GetBytes(char); } } public class Foo { public byte [] GetBytes< TSource> (TSource输入) { BitConverter.GetBytes(input); $ div $解析方案
更一般地说,我如何创建一个通用方法来调用基于泛型参数类型的非泛型方法?
一般来说,除非所涉及的方法以 System.Object 作为参数,否则不能。问题在于泛型并不仅限于方法调用参数所允许的类型。
最接近的是使用运行时绑定:
public byte [] GetBytes< TSource> (TSource输入) { dynamic obj = input; BitConverter.GetBytes(obj); $ b这会将方法绑定逻辑推送到运行时,请拨打适当的方式。
Why does the following code not compile? How can I create a generic method which calls the appropriate "BitConverter.GetBytes" overload based on if the generic type is an "int", "bool", "char", etc.? More generally, how can I create a generic method which calls a non-generic method based on the generic parameter's type?
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); } }解决方案
More generally, how can I create a generic method which calls a non-generic method based on the generic parameter's type?
In general, you can't, unless the method in question takes System.Object as a parameter. The problem is that the generic isn't constrained to just types that would be allowed by the method call arguments.
The closest you can do is to use runtime binding:
public byte[] GetBytes <TSource> (TSource input) { dynamic obj = input; BitConverter.GetBytes(obj); }This pushes the method binding logic to runtime, and will throw if there isn't an appropriate method to call.
更多推荐
如何使用泛型将参数传递给非泛型方法?
发布评论