[英]How to determine whether an object can be convert to meaningful string in C#
I need to determine whether the ToString() method of an object will return a meaningful string instead of its class name. 我需要确定对象的ToString()方法是否将返回有意义的字符串而不是其类名。 For example, bool, int, float, Enum, etc. returns meaningful string, instead an instance of ArrayList will return "System.Collections.ArrayList".
例如,bool,int,float,Enum等返回有意义的字符串,而ArrayList的实例将返回“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()
? 你可以将
object.GetType().ToString()
object.ToString()
与object.GetType().ToString()
进行比较object.GetType().ToString()
?
Kindness, 善良,
Dan 担
You can use reflection to check if class of object overrides toString. 您可以使用反射来检查对象类是否覆盖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. 更新 - 查看是否有任何基类具有非来自Object的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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.