i have this two classes:
Item<T> : BusinessBase<T> where T : Item<T>
{
public static T NewItem()
{
//some code here
}
}
Video : Item <Video>
{
}
now i want to invoke NewItem() method on class Video using reflection. when i try with this:
MethodInfo inf = typeof(Video).GetMethod("NewItem", BindingFlags.Static);
the object inf after executing this line still is null. can i invoke static NewItem() method on class Video?
After we have the class instance, we can get the public static method object by calling the getMethod method. Once we hold the method object, we can invoke it simply by calling the invoke method. It's worthwhile to explain the first argument of the invoke method.
invoke(Object obj, Object[] args) , "If the underlying method is static, then the specified obj argument is ignored. It may be null." So, instead of passing in an actual object, a null may be passed; therefore, a static method can be invoked without an actual instance of the class.
You need to specifiy BindingFlags.Public and BindingFlags.FlattenHierarchy in addition to BindingFlags.Static:
MethodInfo inf = typeof(Video).GetMethod("NewItem",
BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
Alternatively, you can get the method from the declaring type without BindingFlags.FlattenHierarchy:
MethodInfo inf = typeof(Item<Video>).GetMethod("NewItem",
BindingFlags.Static | BindingFlags.Public);
I've tried both ways and they both work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With