2012-08-09 47 views
1

這就是我想要做一個假例如:妙傳反射得到一個類泛型方法

var ass = Assembly.Load("Dummy.Class.FullName"); 

var yy = 
    from t in ass.GetTypes() 
    let attributes = t.GetCustomAttributes(typeof(MyTestAttribute), true) 
    where attributes != null && attributes.Length > 0 
    select new { Type = t, Attributes = attributes.Cast<MyTestAttribute>() }; 

foreach (var x in yy) 
{ 
    TestOpen<typeof(x.Type)>(); 
} 

private void TestOpen<TEntity>() where TEntity : Entity, new() 
{ 
} 

我不能得到一個類定義,並傳遞到一個通用的方法就這樣,我嘗試了一切,我想我錯過了特別的東西,該方法正在等待一些編譯類,從反射我不能得到這個,正確的?

歡呼

回答

1

您可以使用MakeGenericMethod生成適當的方法定義,並通過反射調用它。

Type thisType = this.GetType(); 

var mi = thisType.GetMethod("TestOpen"); 

foreach (var x in yy) 
{ 
    var gmi = mi.MakeGenericMethod(x.Type); 
    gmi.Invoke(this, null); 
} 
+0

Thanks @Reed!在這個例子中,我的Dummy示例工作正常,但我試圖在Relay命令中輸入......它不能很好地工作。 VAR RCOM =新RelayCommand(this.TestOpen ,()=>真) 私人無效TestOpen ()其中TEntity:實體,新的() { } – 2Fast4YouBR 2012-08-09 16:49:26

+1

@ 2Fast4YouBR很難確定,但你可能想要:'var rcom = new RelayCommand(()=> gmi.Invoke(this,null),()=> true);' – 2012-08-09 16:53:09

+0

@ 2Fast4YouBR gmi.Invoke正在調用TestOpen for你... – 2012-08-09 16:53:30