【问题标题】:Is there any reasonable use for String.ToString?String.ToString 有什么合理的用途吗?
【发布时间】:2012-11-29 02:01:11
【问题描述】:

我刚看到这个

string response = GetResponse();
return response.ToString();

使用ToString()方法有什么合理的解释吗?

【问题讨论】:

  • 没有。 string.ToString() 是空操作 (return this)

标签: c# string object clone tostring


【解决方案1】:

不,没有。 它可用的唯一原因是,因为它来自 Object。 (并且String继承自Object)

【讨论】:

  • 好吧,字符串确实提供了自己的实现;它不是只是来自object
  • String.toString():这个对象(已经是一个字符串!)本身被返回。
    Object.toString():Object 类的 toString 方法返回一个字符串,该字符串由该对象作为实例的类的名称、at 符号字符“@”和无符号的十六进制表示形式组成。对象的哈希码。也就是说,这个方法返回一个等于
    值的字符串取自:docs.oracle.com
  • 这就是我的观点(尽管我不确定 Oracle 和 @hashcode 的来源)。
【解决方案2】:

这没有任何作用,来自 ILSpy:

public override string ToString()
{
    return this;
}

但也许他想强制NullReferenceException,尽管那会not be best-practise

【讨论】:

    【解决方案3】:

    没有区别。没有必要再次将字符串转换为字符串。我认为正确的代码必须如下:

    WebResponse response = GetResponse();
    return response.ToString();
    

    GetResponse() 返回 WebResponse 对象。

    【讨论】:

      【解决方案4】:

      从技术上讲,标记的答案是正确的,但我想在这里的答案中引入多态性的概念。有理由使用 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 会返回自身并且这是合理的(尽管是迂回的)使用来回到核心题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-06
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多