相关疑难解决方法(0)

如何使用反射来调用泛型方法?

当在编译时未知类型参数但是在运行时动态获取时,调用泛型方法的最佳方法是什么?

考虑以下示例代码 - 在Example()方法内部,GenericMethod<T>()使用Type存储在myType变量中调用的最简洁方法是什么?

public class Sample
{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // What goes here to call GenericMethod<T>()?
        GenericMethod<myType>(); // This doesn't work

        // What changes to call StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {
        // ...
    }

    public static void StaticMethod<T>()
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

c# generics reflection

1002
推荐指数
6
解决办法
24万
查看次数

在运行时指定泛型集合类型参数

我有:

class Car {..}
class Other{
  List<T> GetAll(){..}
}
Run Code Online (Sandbox Code Playgroud)

我想要做:

Type t = typeof(Car);
List<t> Cars = GetAll<t>();
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

我想从运行时使用反射发现的类型的数据库中返回一个泛型集合.

c# generics casting runtime

25
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

generics ×2

casting ×1

reflection ×1

runtime ×1