当对象确实是字符串时,将对象转换为字符串与将对象转换为字符串 [英] Casting vs Converting an object toString, when object really is a string

查看:34
本文介绍了当对象确实是字符串时,将对象转换为字符串与将对象转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个真正的问题,但是我很好奇.当我将一个字符串保存在一个 DataRow 中时,它会被转换为 Object.当我想使用它时,我必须将它转换为 ToString.据我所知,有几种方法可以做到这一点,首先是

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

另一个是:

string name = DataRowObject["name"].ToString();

我对两者有什么区别感兴趣?第一个更有效率吗?(这只是一个推测,在我的脑海中 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?

推荐答案

两者适用于不同的目的.任何的 ToString 方法对象应该返回一个字符串该对象的表示.铸件完全不同,as"键word 执行条件转换,如已经说过.作为"关键字基本上说给我一个参考这个类型到那个对象,如果对象是这种类型"而 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

这篇关于当对象确实是字符串时,将对象转换为字符串与将对象转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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