Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何基于类型对象对函数进行泛型调用?_C#_.net 4.0 - Fatal编程技术网

C# 如何基于类型对象对函数进行泛型调用?

C# 如何基于类型对象对函数进行泛型调用?,c#,.net-4.0,C#,.net 4.0,当所有的是:T表示为类型对象时,如何执行Get Type type=typeof(int); 参数param1和param2 public void DoCall(){ var type=typeof(int); // object o=Get<type> ("p1","p2"); //<-- wont work (expected) // *** what should go here? *** }

当所有的是:T表示为类型对象时,如何执行Get

Type type=typeof(int);
参数param1和param2

    public void DoCall(){
        var type=typeof(int);
        // object o=Get<type> ("p1","p2");   //<-- wont work (expected)
        // *** what should go here? ***
    }

    public IEnumerable<T> Get<T>(string param1,string param2) {
        throw new NotImplementedException();
    }
public void DoCall(){
变量类型=类型(int);
//对象o=Get(“p1”、“p2”);//是键:

var get = typeof(WhereverYourGetMethodIs).GetMethod("Get");
var genericGet = get.MakeGenericMethod(type);

直接使用泛型类型参数有什么不对

public void DoCall(){
    IEnumerable<int> integers = Get<int> ("p1","p2");
    // ...
}
public void DoCall(){
IEnumerable integers=Get(“p1”、“p2”);
// ...
}

在上面的示例中,“T”将是传入Get方法的任何内容,它也将返回相同的IEnumerable。因此,如果执行以下操作:

 IEnumerable<int> o = Get<int>("p1", "p2");
IEnumerable o=Get(“p1”、“p2”);
o将是数不清的


但是,如果您需要其他类型,则只需传入不同的类型,因此是泛型类型。

您需要使用反射:

public IEnumerable GetBoxed(Type type, string param1, string param2)
{
    return (IEnumerable)this
        .GetType()
        .GetMethod("Get")
        .MakeGenericMethod(type)
        .Invoke(this, new[] { param1, param2 });
}

如果可能,您应该重新定义Get方法,将对象类型作为参数:

public IEnumerable<object> Get(object type, string param1,string param2)
{
}
public IEnumerable Get(对象类型,字符串参数1,字符串参数2)
{
}
然后,如果您确实需要它,您可以按如下方式重写原始的泛型方法:

public IEnumerable<T> Get<T>(string param1,string param2)
{
    var result = Get(typeof(T), param1, param2);
    return result.Cast<T>();
}
public IEnumerable Get(字符串param1,字符串param2)
{
var结果=Get(类型(T),参数1,参数2);
返回result.Cast();
}

这种泛型方法是为了编译时的类型安全。如果您在编译时不知道该类型,则很有可能您使用的泛型是错误的,或者应该有一个额外的重载,该重载将该类型作为参数,例如
public IEnumerable Get(type type,string param1,string param2)
@jamice:谢谢你的评论jamice。我会记住这一点。保留的一个原因是我希望尽可能使用。我必须放弃在这种情况下的使用,或者采用两个方法签名(一个带有Get,另一个带有Get(Type typ,…)@sgtz-有2种方法是处理这两种可能性的常用方法。这是大多数DA库处理这种情况的方式。+1看起来很接近。我们是否也应该为“MakeGenericMethod”提供参数?