使用反射和 C# 调用静态方法时遇到问题 [英] trouble invoking static method using reflection and c#
本文介绍了使用反射和 C# 调用静态方法时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这两个类:
Item<T> : BusinessBase<T> where T : Item<T>
{
public static T NewItem()
{
//some code here
}
}
Video : Item <Video>
{
}
现在我想使用反射在类 Video 上调用 NewItem() 方法.当我尝试这样做时:
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);
执行此行后的对象inf 仍然为空.我可以在类 Video 上调用静态 NewItem() 方法吗?
the object inf after executing this line still is null. can i invoke static NewItem() method on class Video?
推荐答案
您需要指定 BindingFlags.公共 和 BindingFlags.FlattenHierarchy 以及 BindingFlags.静态:
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);
或者,您可以从没有的声明类型中获取方法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# 调用静态方法时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文