【发布时间】:2013-08-12 15:45:10
【问题描述】:
为什么我不能Class.GetMethod(string) 但我可以this.GetType().GetMethod(string)?
我想做前者,因为我已经知道要在哪个类中搜索,这似乎会快很多...
【问题讨论】:
标签: c#
为什么我不能Class.GetMethod(string) 但我可以this.GetType().GetMethod(string)?
我想做前者,因为我已经知道要在哪个类中搜索,这似乎会快很多...
【问题讨论】:
标签: c#
【讨论】:
Class.GetMethod(string) is 仍在使用字符串...我以为您只想摆脱对this.GetType(string)的调用-事实上,它甚至无法编译。
【讨论】:
嗯,你可以做任何一个:
typeof (MyClass).GetMethod("MyMethod");
或
MyClass myClass = new MyClass();
myClass.GetType().GetMethod("MyMethod");
只需添加 - myClass.GetType().GetMethod("MyMethod") - 在运行时解析,其中 typeof(MyClass).GetMethod("MyMethod") 在编译时解析。
Here 有点多。
【讨论】:
Type 类的GetMethod 方法。第二个示例尝试在 MyClass 类型上调用 GetMethod。如果MyClass 没有定义名为GetMethod 的方法,则会产生编译错误。也许你的意思是你的第二个例子是myClass.GetType().GetMethod("MyMethod")?