C# 从基类内部获取派生类型的名称

发布于 2024-08-03 14:51:46 字数 156 浏览 2 评论 0原文

在调试会话期间,对我来说,在特定实例的调试信息中识别实际派生类的名称非常重要。

我尝试使用 this.GetType().Name 但这只是返回 base 类的类型。

有没有一种简单的方法可以从基类中获取派生类的类型?

During a debug session, it's important for me to identify the name of the actual derived class in the debug info of specific instances.

I tried using this.GetType().Name but this simply returns the type of the base class.

Is there a simple way to get the type of the derived class from within the base class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

誰ツ都不明白 2024-08-10 14:51:46

this.GetType().Name 应该可以工作。我认为,就您而言,您可能没有派生类。如果它返回基类名称,则它不应该有派生类。

使用此功能:

  1. 基类 - 输出基类名称
  2. 派生类 - 输出派生类名称
  3. 派生类转换为基类 - 输出派生类名称
  4. 派生类传递到接受基类作为参数的函数 - 输出派生类名称

this.GetType().Name should work. I think, in your case, you may not have a derived class. If it's returning the base class name, it shouldn't have a derived class.

Using this on:

  1. Base class - Outputs Base class name
  2. Derived class - Outputs Derived class name
  3. Derived class cast to Base class - Outputs Derived class name
  4. Derived class passed into a function that accepts Base class as a parameter - Outputs Derived class name
澉约 2024-08-10 14:51:46

this.GetType().Name 始终返回当前执行类型的名称,而不是编写代码的类型。不过,您可以使用 Debugger.Break( ) 以有条件的方式:

if (this.GetType().Name == "Problematic type")
    System.Diagnostics.Debugger.Break();

this.GetType().Name always return the name of the current executing type, not the type that the code that it was written in. You can emulate breakpoints though, using Debugger.Break() in a conditional manner:

if (this.GetType().Name == "Problematic type")
    System.Diagnostics.Debugger.Break();
挖个坑埋了你 2024-08-10 14:51:46

在调试会话期间...

请记住,不是停止会话来添加一些一次性代码,然后重新编译并重新启动,而是可以在命中断点后使用调试器来推测这一点

...利用调试器的立即窗口并在相关实例中键入this.GetType().Name,然后按Enter,它将显示。

请参阅 VS 文档:立即窗口

有没有一种简单的方法可以从基类中获取派生类的类型?

是的,举个例子,我可以通过使用 GetTypeName 属性实时确定异常是什么:

在此处输入图像描述

During a debug session...

Remember that instead halting a session to add some throw-away code to then recompile and restart, one can use the debugger to divine that after the breakpoint is hit...

By utilizing the Immediate Window of the debugger and typing a this.GetType().Name off of the instance in question and then pressing Enter, it will be shown.

See VS Docs: Immediate Window

Is there a simple way to get the type of the derived class from within the base class?

Yes, for an example I can determine what the exception is by using the Name property of GetType and in real time:

enter image description here

旧城空念 2024-08-10 14:51:46

引发事件时,请务必将真正的发送者传递给发送者属性。侦听类中的发送者对象应正确指向引发事件的子类。

When raising an event, be sure to pass the real sender to the sender property. The sender object in the listening class should correctly point to the child class that raised the event.

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