所以我有這個自定義對象,採取類型調用/靜態函數:如何用類型調用函數?
MyObject<MyType>.MyFunction();
的MyObject被定義爲這樣的:
public abstract class MyObject <type> { ... }
如何調用它?我需要調用的原因是MyType是動態的,我不能這樣做:
Type t = this.GetType();
MyObject<t>.MyFunction();
所以我有這個自定義對象,採取類型調用/靜態函數:如何用類型調用函數?
MyObject<MyType>.MyFunction();
的MyObject被定義爲這樣的:
public abstract class MyObject <type> { ... }
如何調用它?我需要調用的原因是MyType是動態的,我不能這樣做:
Type t = this.GetType();
MyObject<t>.MyFunction();
你需要使用反射來實例化類 - 然後更多的反射調用方法:
Type typeDefinition = typeof(MyObject<>);
Type constructedType = typeDefinition.MakeGenericType(t);
MethodInfo method = constructedType.GetMethod("MyFunction");
method.Invoke(null, null);
這是不愉快的,當然。你肯定需要它是一個泛型類中的方法嗎?
您是否知道關鍵字typeof?
這應該只是罰款:msdn.microsoft.com/en-us/library/twcad0zb(v=vs.80).aspx
typeof(MyObject<>).MakeGenericType(this.GetType())
.GetMethod("MyFunction", BindingFlags.Static | BindingFlags.Public)
.Invoke(null, null);
只能使用反射。
typeof(MyObject<>).MakeGenericType(t).GetMethod("MyFunction", BindingFlags.Static).Invoke(null, new object[0]);
您是否知道關鍵字typeof?這應該工作得很好:http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.80).aspx – Codeman 2012-07-24 18:19:33