c# - 当对象确实是一个字符串时,转换与将对象转换为字符串

标签 c# string casting parsing

这不是真正的问题,但我很好奇。当我在假设一个 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/

相关文章:

c# - 从任务并行库问题更新 UI

c# - .NET WPF 记住 session 之间的窗口大小

c - 为什么在 C 语言中退出 do-while 循环请求输入后程序会崩溃?

c++ - 将 float 转换为 int 时的奇怪行为

ios - 使用自定义对象 ios 键入 Cast

c# - 如何从以特定名称开头的 appsettings 键中获取所有值并将其传递给任何数组?

c# - 删除已经绘制的形状

python - 字符串到列表的Python转换

string - VBScript 有 substring() 函数吗?

java - 在 Java 中是否有首选的对象转换方法?