How to determine if an object can be converted to a meaningful string in C #

I need to determine if the object's ToString () method will return a meaningful string instead of the class name. For example, bool, int, float, Enum, etc. Returns a meaningful string; instead, an ArrayList instance returns "System.Collections.ArrayList". If there is an easy way to archive this?

Thanks in advance.

Regards, Wayne

+3
source share
2 answers

Can you compare object.ToString()with object.GetType().ToString()?

Kindness,

Dan

+24
source

You can use reflection to check if an object class overrides toString. Like this

if (obj.GetType().GetMethod("toString",
    BindingFlags.Instance |
    BindingFlags.Public |
    BindingFlags.DeclaredOnly) != null)
{
    // do smth
}

- , - toString, .

        MethodInfo pi = null;
        Type t = obj.GetType(0;
        while (t != typeof(object) && pi == null)
        {
            pi = t.GetMethod("toString",
                BindingFlags.Instance |
                BindingFlags.Public | 
                BindingFlags.DeclaredOnly);
            t = t.BaseType;
        }

        if (pi != null)
        {
            // do smth
        }
+3

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


All Articles