Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble invoking static method using reflection and c#

Tags:

c#

reflection

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?

like image 550
backdoor Avatar asked Sep 22 '10 14:09

backdoor


People also ask

How do you call a static method in a reflection?

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.

Can a static method be invoked?

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.


1 Answers

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.

like image 143
dtb Avatar answered Nov 07 '22 14:11

dtb