trouble invoking static method using reflection an

2019-04-19 11:09发布

问题:

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?

回答1:

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.



标签: c# reflection