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
}
精彩评论