开发者

How to determine whether an object can be convert to meaningful string in C#

开发者 https://www.devze.com 2022-12-11 00:42 出处:网络
I need开发者_C百科 to determine whether the ToString() method of an object will return a meaningful string instead of its class name. For example, bool, int, float, Enum, etc. returns meaningful strin

I need开发者_C百科 to determine whether the ToString() method of an object will return a meaningful string instead of its class name. For example, bool, int, float, Enum, etc. returns meaningful string, instead an instance of ArrayList will return "System.Collections.ArrayList". If there a simple way to archive that?

Thanks in advance.

Regards, Wayne


You could compare object.ToString() with object.GetType().ToString() ?

Kindness,

Dan


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

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

Update - see if any base class has toString implementation that is not from Object.

        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
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消