trouble invoking static method using reflection an

2019-04-19 11:03发布

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?

标签: c# reflection
1条回答
一纸荒年 Trace。
2楼-- · 2019-04-19 11:42

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.

查看更多
登录 后发表回答