2009-05-01 36 views
1

如果我将用户定义对象的类名称作为字符串,如何在泛型函数中将其用作对象的类型?如何根据类名获取用户定义的对象类型?

SomeGenericFunction(objectID);

+0

我们将需要一些我认为更多的信息。你能写一些你想做的事情的示例代码,即使它不起作用吗? – Mykroft 2009-05-01 13:19:04

回答

5

如果你有一个字符串,然后做的第一件事就是用Type.GetType(string),或(最好)Assembly.GetType(string)得到Type实例。从那里,你需要使用反射:静态方法

Type type = someAssembly.GetType(typeName); 
typeof(TypeWithTheMethod).GetMethod("SomeGenericFunction") 
      .MakeGenericMethod(type).Invoke({target}, new object[] {objectID}); 

其中{target}是实例方法的实例,null

例如:

using System; 
namespace SomeNamespace { 
    class Foo { } 
} 
static class Program { 
    static void Main() { 
     string typeName = "SomeNamespace.Foo"; 
     int id = 123; 
     Type type = typeof(Program).Assembly.GetType(typeName); 
     object obj = typeof(Program).GetMethod("SomeGenericFunction") 
      .MakeGenericMethod(type).Invoke(
       null, new object[] { id }); 
     Console.WriteLine(obj); 
    } 
    public static T SomeGenericFunction<T>(int id) where T : new() { 
     Console.WriteLine("Find {0} id = {1}", typeof(T).Name, id); 
     return new T(); 
    } 
} 
0

查看System.Type.GetType()方法 - 提供完全限定的类型名称,并返回相应的Type对象。然后,您可以做这样的事情:

namespace GenericBind { 
    class Program { 
     static void Main(string[] args) { 
      Type t = Type.GetType("GenericBind.B"); 

      MethodInfo genericMethod = typeof(Program).GetMethod("Method"); 
      MethodInfo constructedMethod = genericMethod.MakeGenericMethod(t); 

      Console.WriteLine((string)constructedMethod.Invoke(null, new object[] {new B() })); 
      Console.ReadKey(); 
     } 

     public static string Method<T>(T obj) { 
      return obj.ToString(); 
     } 
    } 

    public class B { 
     public override string ToString() { 
      return "Generic method called on " + GetType().ToString(); 
     } 
    } 
} 
+0

私有类识别TestClass:BaseClass的{ 公共识别TestClass(长ID):碱(ID) { } } – user99322 2009-05-01 13:52:21

相关问题