c# – 如何使用泛型将参数传递给非泛型方法?

前端之家收集整理的这篇文章主要介绍了c# – 如何使用泛型将参数传递给非泛型方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么以下代码无法编译?
如何创建一个泛型方法,根据泛型类型是“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);
    }
}

解决方法

More generally,how can I create a generic method which calls a non-generic method based on the generic parameter’s type?

通常,您不能,除非有问题的方法将System.Object作为参数.问题是泛型不仅限于方法调用参数允许的类型.

您最接近的是使用运行时绑定:

public byte[] GetBytes <TSource> (TSource input)
{
     dynamic obj = input;
     BitConverter.GetBytes(obj);
}

这会将方法绑定逻辑推送到运行时,如果没有适当的方法可以调用,则会抛出.

原文链接:https://www.f2er.com/csharp/94802.html

猜你在找的C#相关文章