如果在运行时只知道类型参数,如何调用generics方法?
我有这个方法:
public List SomeMethod( params ) where T : new()
所以我想把这个SomeMethod
,如果我知道这个类型就好了:
SomeMethod();
但如果我在运行时只有Class1
,我就无法调用它?
那么如何用未知的T类型调用SomeMethod
? 我用reflection得到了Type。
我有Type类型,但SomeMethod
SomeMethod
不起作用。
更新7. May:
以下是我想要实现的示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication63 { public class DummyClass { } public class Class1 { public string Name; } class AssemblyTypesReflection { static void Main(string[] args) { object obj = new Class1() { Name = "John" } ; Assembly assembly = Assembly.GetExecutingAssembly(); var AsmClass1 = (from i in assembly.GetTypes() where i.Name == "Class1" select i).FirstOrDefault(); var list = SomeMethod((AsmClass1)obj); //Here it fails } static List SomeMethod(T obj) where T : new() { return new List { obj }; } } }
这是一个从更大的背景中获取的演示。
你需要使用reflection来调用它:
var method = typeof(SomeClass).GetMethod("SomeMethod"); method.MakeGenericMethod(someType).Invoke(...);
您可以在C#4中使用dynamic
关键字。您还需要.NET 4.0或更高版本:
SomeMethod((dynamic)obj);
运行时会推断出实际的类型参数并进行调用。 如果obj
为null则失败,因为那时没有类型信息。 C#中的null没有类型。