如何确定对象是否可以将ToString转换为值或类型名称? [英] How can I determine if an object can ToString into value or type name?

查看:157
本文介绍了如何确定对象是否可以将ToString转换为值或类型名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写php服务和我们的crm之间的互操作.我需要做的一件事是确保将简单类型转换为ToString()以便以后在json转换器中使用.

I am writing an interop between a php service and our crm. One of the things I need to do is make sure that simple types get converted ToString() for use later in a json converter.

我什至不确定简单类型"的名称是什么,但是可以这样定义...一个代表低级变量类型的对象,它包含单个值,而不是类或任何具有可执行文件的对象功能等"

I am not sure even what the name is for 'simple types' but it can be defined like this... "an object that represents a low level variable type, containing a single value, not a class or anything with executable functions etc"

我发现int,string,bool,double和令人惊讶的枚举将对ToString()产生可预测的结果.

I've found that int, string, bool, double, and surprisingly enum will ToString() with pretty predictable results.

int x = 0;
bool y = true;
double z = 1.59 // money
CustomEnum theEnum = CustomEnum.somevalue;

x.ToString()的结果为"0"

x.ToString() results in "0"

y.ToString()结果为真"

y.ToString() results in "true"

z.ToString()的结果为"1.59"

z.ToString() results in "1.59"

theEnum.ToString()结果为"somevalue"

theEnum.ToString() results in "somevalue"

但是如果我使用这个:

List<int> iList = new List<int>();
iList.Add(1);

MyClass theClass = new MyClass();

iList.ToString()生成"System.Collections.Generic.List`1 [System.Int32]" theClass.ToString()结果为"STTI.NKI.Interop.MyClass"

iList.ToString() results in "System.Collections.Generic.List`1[System.Int32]" theClass.ToString() results in "STTI.NKI.Interop.MyClass"

我不仅限于列表.我可以有一个ExpandoObject或一个类等.

I'm not limited to lists. I could have an ExpandoObject, or a class etc.

我完全理解为什么会发生这种情况,并且我想知道是否有一种快速的方法来确定未知类型的对象是否会将ToString()转换为期望值,而不是类型名称.我发现做类似的事情是反模式

I understand EXACTLY why this happens, and I want to know if there is a quick way to determine if an object of unknown type will ToString() into an expected value, and not the type name. I find it an antipattern to do something like

switch (theObject.GetType())
 case typeof(int):
 case typeof(bool):
 case typeof(doulble):
etc

我不确定这些术语是什么,因此谷歌搜索我的答案非常困难.

I am not sure what the terms are, so googling my answer is proving difficult.

推荐答案

所以您要检查类型是否具有覆盖的ToString方法?为什么不只检查ToString返回的值是否等于ToString的默认实现返回的值?

So you want to check whether a type has a overridden ToString method? Why not just check whether the value returned by ToString is equal to the value returned by the default implementation of ToString?

此处,我们知道

From here, we know the default implementation of ToString is

return GetType().ToString();

因此,我们可以使用它来检查对象是否已覆盖ToString方法:

So, we can use this to check whether an object has overridden the ToString method:

bool toStringOverridden = someObject.GetType().ToString() !=
    someObject.ToString();

这篇关于如何确定对象是否可以将ToString转换为值或类型名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆