Is there any way to tell if an object implemented ToString explicitly in C #

I am trying to write down the state information of some objects and classes in my code. Not all classes or libraries have been implemented using Serialization. Therefore, I use Reflection for properties to write an XML status document. However, I have a problem in that some objects, such as inline classes (e.g. strings, DateTime, Numbers, etc.), have a ToString function that significantly displays the value of the class. But for other classes, a ToString call simply uses the inherited ToString base to spit out the object type name (for example, a dictionary). In this case, I want to recursively examine the properties inside this class.

So, if someone can help me with thinking or figuring out if there is a ToString implemented in the property I'm looking for, this is not a basic method or to indicate the correct way to use GetValue to get the properties of the collection I would appreciate it.

J

+6
source share
1 answer

To determine if the default method overrides MethodInfo.DeclaringType .ToString() check MethodInfo.DeclaringType like this:

 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 
+10
source

Source: https://habr.com/ru/post/897786/


All Articles