2012-07-24 48 views
2

所以我有這個自定義對象,採取類型調用/靜態函數:如何用類型調用函數?

 MyObject<MyType>.MyFunction(); 

的MyObject被定義爲這樣的:

 public abstract class MyObject <type> { ... } 

如何調用它?我需要調用的原因是MyType是動態的,我不能這樣做:

 Type t = this.GetType(); 
    MyObject<t>.MyFunction(); 
+1

您是否知道關鍵字typeof?這應該工作得很好:http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.80).aspx – Codeman 2012-07-24 18:19:33

回答

4

你需要使用反射來實例化類 - 然後更多的反射調用方法:

Type typeDefinition = typeof(MyObject<>); 
Type constructedType = typeDefinition.MakeGenericType(t); 
MethodInfo method = constructedType.GetMethod("MyFunction"); 
method.Invoke(null, null); 

這是不愉快的,當然。你肯定需要它是一個泛型類中的方法嗎?

+0

使用反射得到一個通用的方法感到討厭我...有沒有原因OP不能僅僅使用標準的通用樣板文件? – Codeman 2012-07-24 18:21:50

+0

打敗我吧。 +1 – 2012-07-24 18:23:05

+0

上帝是不愉快的...... – Bill 2012-07-24 18:31:01

1
typeof(MyObject<>).MakeGenericType(this.GetType()) 
    .GetMethod("MyFunction", BindingFlags.Static | BindingFlags.Public) 
    .Invoke(null, null); 
1

只能使用反射。

typeof(MyObject<>).MakeGenericType(t).GetMethod("MyFunction", BindingFlags.Static).Invoke(null, new object[0]);