【发布时间】:2012-11-29 02:01:11
【问题描述】:
我刚看到这个
string response = GetResponse();
return response.ToString();
使用ToString()方法有什么合理的解释吗?
【问题讨论】:
-
没有。
string.ToString()是空操作 (return this)
标签: c# string object clone tostring
我刚看到这个
string response = GetResponse();
return response.ToString();
使用ToString()方法有什么合理的解释吗?
【问题讨论】:
string.ToString() 是空操作 (return this)
标签: c# string object clone tostring
不,没有。 它可用的唯一原因是,因为它来自 Object。 (并且String继承自Object)
【讨论】:
object。
@hashcode 的来源)。
这没有任何作用,来自 ILSpy:
public override string ToString()
{
return this;
}
但也许他想强制NullReferenceException,尽管那会not be best-practise。
【讨论】:
没有区别。没有必要再次将字符串转换为字符串。我认为正确的代码必须如下:
WebResponse response = GetResponse();
return response.ToString();
GetResponse() 返回 WebResponse 对象。
【讨论】:
从技术上讲,标记的答案是正确的,但我想在这里的答案中引入多态性的概念。有理由使用 string.ToString,它只是间接的。
考虑以下场景:
string s = "my groovy string";
object o = s; //This or something like this could happen for many reasons but this is an example so don't analyze this simplicity.
Console.Write( o.ToString() ); //We are technically calling string.ToString() leading to the code in Tim's answer where we return this.
除了ToString 是在Object 上定义的这一事实之外,这就是为什么string.ToString 会返回自身并且这是合理的(尽管是迂回的)使用来回到核心题。
【讨论】: