铸造VS转换对象的toString,当物体确实是一个字符串 [英] Casting vs Converting an object toString, when object really is a string
问题描述
这是不是一个真正的问题,但是我很好奇。当我保存一个字符串中可以说一个的DataRow,它被转换为对象。当我想用它,我一定要投它的ToString。据我知道有这样做的几种方法,第一个是
字符串名称=(字符串)DataRowObject [名称]; //有效的,因为我知道这是一个字符串
和另一个是:
字符串名称= DataRowObject [名称]的ToString()。
我感兴趣的是在两者之间有什么区别?是第一个更有效率? (这只是一种炒作,在我的脑海ToString()方法是通过一些循环机制,即只有投它可能会更快实现,然而,这只是一种直觉我有)。
时甚至有这样做的更快/更优雅的方式?
任何人都可以清除此为我?
两个旨在用于不同
目的。任何ToString方法
对象应该返回字符串
再这个对象的presentation。铸件
是完全不同的,而'为'键
词在一定条件下转换,如
已经说了。在'为'关键字
基本上说给我拿的参考
这种类型的到该对象,如果该
对象是这种类型的ToString时
说给我一个重新串presentation
该对象的,其结果可能是
同样在某些情况下,但两者应该
从未被认为可互换
因为,正如我所说,他们的存在
不同的目的。如果你的意图
是投那么你应该总是使用
铸造,NOT的ToString。
块引用>从<一个href=\"http://www.$c$cguru.com/forum/showthread.php?t=443873\">http://www.$c$cguru.com/forum/showthread.php?t=443873
又见<一个href=\"http://bytes.com/groups/net-c/225365-tostring-string-cast\">http://bytes.com/groups/net-c/225365-tostring-string-cast
This isn't really an issue, however I am curious. When I save a string in lets say an DataRow, it is cast to Object. When I want to use it, I have to cast it ToString. As far as I know there are several ways of doing this, first is
string name = (string)DataRowObject["name"]; //valid since I know it's a string
and another one is:
string name = DataRowObject["name"].ToString();
I am interested in what is the difference between both? Is the first more efficient? (This is just a speculation, in my head ToString() method is implemented by some looping mechanism where just casting it "could" be faster, however this is just a "gut feeling" I have).
Is there even a faster / more elegant way of doing this?
Can anyone clear this up for me?
解决方案The two are intended for different purposes. The ToString method of any object is supposed to return a string representation of that object. Casting is quite different, and the 'as' key word performs a conditional cast, as has been said. The 'as' key word basically says "get me a reference of this type to that object if that object is this type" while ToString says "get me a string representation of that object". The result may be the same in some cases but the two should never be considered interchangeable because, as I said, they exist for different purposes. If your intention is to cast then you should always use a cast, NOT ToString.
from http://www.codeguru.com/forum/showthread.php?t=443873
see also http://bytes.com/groups/net-c/225365-tostring-string-cast
这篇关于铸造VS转换对象的toString,当物体确实是一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!