Is there a way to tell if an object has implemented ToString explicitly in c#

梦想的初衷 提交于 2019-12-22 05:20:05

问题


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


回答1:


To determine whether a method has overridden the default .ToString() check MethodInfo.DeclaringType like so:

void Main()
{
    Console.WriteLine(typeof(MyClass).GetMethod("ToString").DeclaringType != typeof(object));
    Console.WriteLine(typeof(MyOtherClass).GetMethod("ToString").DeclaringType != typeof(object));
}

class MyClass 
{
    public override string ToString() { return ""; }
}

class MyOtherClass {
}

Prints out:

True
False


来源:https://stackoverflow.com/questions/7507609/is-there-a-way-to-tell-if-an-object-has-implemented-tostring-explicitly-in-c-sha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!