2009-05-01 82 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

相關問題