你能使用反射来找出当前方法正在执行的对象的类型吗?

发布于 2024-12-27 03:36:51 字数 172 浏览 2 评论 0原文

我知道如何获取当前方法(MethodBase.GetCurrentMethod())。

但是,MethodBaseDeclaringType 属性将为我提供定义该方法的类型。

我对运行时实际调用的方法的类型感兴趣。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪漫之都 2025-01-03 03:36:51

如果您指的是对象本身的类型,那么只需使用 this.GetType() 即可?这将为您提供当前方法正在执行的 this 类型。

如果您指的是执行该方法的引用的类型,那么实际上无法确定。以虚拟方法为例。

abstract class Animal {
  public abstract void MakeNoise();
}
abstract class Dog : Animal { }
class Labrador : Dog {
  public override void MakeNoise() {
    ...
  }
}

引用类型可以是 Animal,但如果对象是 Labrador,则将调用该版本的 MakeNoise 方法。他们无法从 MakeNoise 方法知道它是否是从 AnimalDogLabrador 调用的实例。

If you mean the type of the object itself then just use this.GetType()? That will give you the type of this 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.

abstract class Animal {
  public abstract void MakeNoise();
}
abstract class Dog : Animal { }
class Labrador : Dog {
  public override void MakeNoise() {
    ...
  }
}

The reference type could be Animal but if the object is Labrador then that version of the MakeNoise method will be invoked. Their is no way from the MakeNoise method to know if it' was invoked from an Animal, Dog or Labrador instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文