2014-02-28 48 views
3

我有一個靜態方法的類:調用靜態方法給它在C#動態類型和參數

public class MyClass { 
    public static bool MyMethod<T>(string arg1) where T : class { 
     // ... 
    } 
} 

我如何可以調用因爲我知道我的類型T應該MyNamespace.Data.Models.Student(這是通過變量提供),arg1的值可以說是student

它與以下內容類似嗎?我不知道如何爲它設置T類型。

Type.GetType("MyClass").GetMethod("MyMethod").Invoke(null, new object[] { arg1 = "student" }) 
+2

可能重複http://stackoverflow.com/ questions/232535/how-to-use-reflection-to-call-generic-method –

回答

4

您正在尋找的MakeGenericMethod方法MethodInfo

Type.GetType("MyClass") 
    .GetMethod("MyMethod") 
    .MakeGenericMethod(typeOfGenericArgument) 
    .Invoke(null, new object[] { "student" }) 
1

您需要GetMethod指定BindingFlags.Static得到一個靜態方法。完成之後,您可以通過MethodInfo.MakeGenericMethod制定一個通用方法來構建適當類型的方法。

+1

除非有一個類似命名的實例方法使其不明確,否則不需要'Static'標誌。 – Servy

3

首先,你應該讓你的方法,並使用MakeGenericMethod這樣的:

var methodType =Type.GetType("MyClass").GetMethod("MyMethod", BindingFlags.Static |BindingFlags.Public); 
var argumentType = typeof (Student); 
var method = methodType.MakeGenericMethod(argumentType); 
method.Invoke(null, new object[] { "student" }); 
相關問題