简体   繁体   English

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

[英]C# Get Name of Derived Type from Inside base Class

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.我尝试使用this.GetType().Name但这只是返回base类的类型。

Is there a simple way to get the type of the derived class from within the base class?有没有一种简单的方法可以从基类中获取派生类的类型?

this.GetType().Name should work. this.GetType().Name应该可以工作。 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派生类传递给接受基类作为参数的函数 - 输出派生类名称

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: this.GetType().Name总是返回当前执行类型的名称,而不是编写它的代码的类型。不过,您可以模拟断点,以有条件的方式使用Debugger.Break()

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

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.通过利用调试器的Immediate Window并键入相关实例的this.GetType().Name ,然后按Enter ,它将显示出来。

See VS Docs: Immediate Window请参阅 VS Docs: 立即窗口

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:是的,例如,我可以通过使用GetTypeName属性实时确定异常是什么:

在此处输入图像描述

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.监听类中的发送者对象应正确指向引发事件的子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM