Reputation: 7782
So I have this custom object / static function that take a Type to call:
MyObject<MyType>.MyFunction();
MyObject is defined as such:
public abstract class MyObject <type> { ... }
How do I invoke it? The reason I need to do invoking is because MyType is dynamic, and I can't do this:
Type t = this.GetType();
MyObject<t>.MyFunction();
Upvotes: 2
Views: 134
Reputation: 5832
Only by using reflection.
typeof(MyObject<>).MakeGenericType(t).GetMethod("MyFunction", BindingFlags.Static).Invoke(null, new object[0]);
Upvotes: 1
Reputation: 12375
Are you aware of the keyword typeof ?
This should work just fine: msdn.microsoft.com/en-us/library/twcad0zb(v=vs.80).aspx
Upvotes: 0
Reputation: 7959
typeof(MyObject<>).MakeGenericType(this.GetType())
.GetMethod("MyFunction", BindingFlags.Static | BindingFlags.Public)
.Invoke(null, null);
Upvotes: 1
Reputation: 1500675
You'd need to use reflection to instantiate the class - and then more reflection to invoke the method:
Type typeDefinition = typeof(MyObject<>);
Type constructedType = typeDefinition.MakeGenericType(t);
MethodInfo method = constructedType.GetMethod("MyFunction");
method.Invoke(null, null);
It's unpleasant, certainly. Do you definitely need it to be a method in a generic class?
Upvotes: 4