你能使用反射来找出当前方法正在执行的对象的类型吗?
我知道如何获取当前方法(MethodBase.GetCurrentMethod()
)。
但是,MethodBase
的 DeclaringType
属性将为我提供定义该方法的类型。
我对运行时实际调用的方法的类型感兴趣。
I know how to get the current method (MethodBase.GetCurrentMethod()
).
However, the DeclaringType
property of MethodBase
will give me the type on which the method is defined.
I am interested in the type of the method on which it was actually called at runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您指的是对象本身的类型,那么只需使用 this.GetType() 即可?这将为您提供当前方法正在执行的
this
类型。如果您指的是执行该方法的引用的类型,那么实际上无法确定。以虚拟方法为例。
引用类型可以是
Animal
,但如果对象是Labrador
,则将调用该版本的MakeNoise
方法。他们无法从MakeNoise
方法知道它是否是从Animal
、Dog
或Labrador
调用的实例。If you mean the type of the object itself then just use
this.GetType()
? That will give you the type ofthis
on which the current method is executing.If you mean the type of the reference on which the method was executed then that's not really possible to determine. Consider virtual methods as an example.
The reference type could be
Animal
but if the object isLabrador
then that version of theMakeNoise
method will be invoked. Their is no way from theMakeNoise
method to know if it' was invoked from anAnimal
,Dog
orLabrador
instance.