这不是真正的问题,但我很好奇。当我在假设一个 DataRow 中保存一个字符串时,它被转换为 Object。当我想使用它时,我必须将它转换为 ToString。据我所知,有几种方法可以做到这一点,首先是
string name = (string)DataRowObject["name"]; //valid since I know it's a string
还有一个是:
string name = DataRowObject["name"].ToString();
我想知道两者之间有什么区别?第一种效率更高吗? (这只是一个推测,在我看来,ToString() 方法是通过某种循环机制实现的,在这种机制中,仅将其转换为“可能”会更快,但这只是我的“直觉”)。
有没有更快/更优雅的方法来做到这一点?
谁能帮我解决这个问题?
最佳答案
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.
来自 http://www.codeguru.com/forum/showthread.php?t=443873
另见 http://bytes.com/groups/net-c/225365-tostring-string-cast
关于c# - 当对象确实是一个字符串时,转换与将对象转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1170756/