C# 从基类内部获取派生类型的名称
在调试会话期间,对我来说,在特定实例的调试信息中识别实际派生类的名称非常重要。
我尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
this.GetType().Name
应该可以工作。我认为,就您而言,您可能没有派生类。如果它返回基类名称,则它不应该有派生类。使用此功能:
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:
this.GetType().Name 始终返回当前执行类型的名称,而不是编写代码的类型。不过,您可以使用 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, usingDebugger.Break()
in a conditional manner:请记住,不是停止会话来添加一些一次性代码,然后重新编译并重新启动,而是可以在命中断点后使用调试器来推测这一点
...利用调试器的
立即窗口
并在相关实例中键入this.GetType().Name
,然后按Enter,它将显示。请参阅 VS 文档:立即窗口
是的,举个例子,我可以通过使用
GetType
的Name
属性实时确定异常是什么: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 athis.GetType().Name
off of the instance in question and then pressing Enter, it will be shown.See VS Docs: Immediate Window
Yes, for an example I can determine what the exception is by using the
Name
property ofGetType
and in real time:引发事件时,请务必将真正的发送者传递给发送者属性。侦听类中的发送者对象应正确指向引发事件的子类。
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.