有没有办法判断一个对象是否在 C# 中显式实现了 ToString
我正在尝试记录有关代码中某些对象和类的状态的信息。并非所有类或库都是通过序列化实现的。因此,我使用 Properties 上的 Reflection 来写出状态的 XML 文档。然而,我面临的挑战是,某些对象(例如内置类(即字符串、日期时间、数字等))具有 ToString 函数,可以以有意义的方式打印出类的值。但对于其他类,调用 ToString 只是使用继承的基 ToString 来吐出对象类型的名称(例如字典)。在这种情况下,我想递归地检查该类内的属性。
因此,如果有人可以帮助我反思,弄清楚我正在查看的属性上是否实现了 ToString,这不是基本方法,或者指出使用 GetValue 检索集合属性的正确方法,我将不胜感激它。
J
I am trying to log information about the state of some objects and classes in my code. Not all the classes or libraries were implemented with Serialization. So I am using Reflection on the Properties to write out an XML document of the state. However, I have a challenge in that some objects like builtin Classes (ie Strings, DateTime, Numbers etc...) have a ToString function that prints out the value of the class in a meaningful way. But for other classes, calling ToString just uses the inherited base ToString to spit out the name of the object type (For example a Dictionary). In that case I want to recursively examine to properties inside that class.
So if anyone can help me with reflection to either figure out if there is a ToString implemented on the property I'm looking at that isn't the base method OR to point out the proper way of using GetValue to retrieve collection properties I would appreciate it.
J
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要确定方法是否覆盖了默认的
.ToString()
,请检查MethodInfo.DeclaringType
,如下所示:打印输出:
To determine whether a method has overridden the default
.ToString()
checkMethodInfo.DeclaringType
like so:Prints out: