2010-10-18 87 views
26

我有一個通用的方法調用帶有類型變量的泛型方法

Foo<T> 

我有一個類型變量bar

是否有可能實現的東西像Foo<bar>

Visual Studio是期望的類型或在酒吧的名字空間。

善良,

+0

你可以在你試圖使用它的地方顯示一些代碼嗎?這是可能的,所以它可能是一個語法錯誤。 – RPM1984 2010-10-18 09:21:01

回答

34

使這種類型讓我們假設foo是在課堂測試中聲明,如

public class Test 
{ 
    public void Foo<T>() { ... } 

} 

您需要先使用實例化類型爲bar的方法210。然後使用反射調用它。

var mi = typeof(Test).GetMethod("Foo"); 
var fooRef = mi.MakeGenericMethod(bar); 
fooRef.Invoke(new Test(), null); 
+0

感謝親切......只是我需要! – 2010-10-18 09:58:18

3

您可以通過

typeof(Foo<>).MakeGenericType(bar); 
20

如果我正確理解你的問題,你已經在本質上,以下類型定義:

public class Qaz 
{ 
    public void Foo<T>(T item) 
    { 
     Console.WriteLine(typeof(T).Name); 
    } 
} 

public class Bar { } 

現在,給你有一個變量bar定義爲這樣:

var bar = typeof(Bar); 

然後,您希望能夠撥打Foo<T>,用您的實例變量bar替換T

方法如下:

// Get the generic method `Foo` 
var fooMethod = typeof(Qaz).GetMethod("Foo"); 

// Make the non-generic method via the `MakeGenericMethod` reflection call. 
// Yes - this is confusing Microsoft!! 
var fooOfBarMethod = fooMethod.MakeGenericMethod(new[] { bar }); 

// Invoke the method just like a normal method. 
fooOfBarMethod.Invoke(new Qaz(), new object[] { new Bar() }); 

享受!

+0

+1 ...比接受的答案晚一點,但是非常棒! – 2010-10-18 09:59:51

+3

@ Daniel Elliot' - 是的,我知道 - 41秒後。我希望我稍微更詳細的答案會佔上風,但唉。 ;-) – Enigmativity 2010-10-18 10:13:23

+0

我的代碼得到工作,詳細的最佳答案....謝謝 – 2016-02-16 10:45:55

相關問題