【问题标题】:Best way to concatenate objects into a single string?将对象连接成单个字符串的最佳方法?
【发布时间】:2013-07-23 19:12:51
【问题描述】:
string resultString = dtMRow("mcode") + "_" + dtRow("pcode")

当我执行上面的代码时,我期望 resultString 被分配给类似 "2356_ASDKJ" 的东西,但我得到了以下异常:

从字符串“_”到类型“Double”的转换无效。

为什么编译器试图将"_" 转换为Double

让它把所有东西都转换成strings的最简单方法是什么?

【问题讨论】:

  • dtMRow("mcode")dtRow("pcode")的数据类型是什么?
  • 很奇怪 - 它应该已经编译... (link)。

标签: c# .net string casting type-conversion


【解决方案1】:

因为 dtMRow 返回双精度?

最好的办法是

String.Format("{0}_{1}", dtMRow("mcode"), dtRow("pcode"));

【讨论】:

  • 很好,很抱歉之前的评论,没有意识到Format 将返回对象的字符串表示 - @DominicKexel
  • @Herdo,您无法编辑答案以添加您自己的想法。如果您认为这不能完全回答问题,请创建您自己的答案。
  • @AshBurlaczenko 我的错。
【解决方案2】:
string resultString = string.format("{0}_{1}", dtMRow("mcode").ToString(), dtRow("pcode").ToString());

我会使用ToString() 来避免装箱操作。

【讨论】:

  • IMO,.ToString() 版本可读性较差,不值得节省任何装箱操作成本。
  • 什么是“装箱操作”?
【解决方案3】:

为什么编译器试图将“_”转换为 Double?

因为dtMRow("mcode")中的类型很可能是doubles

String.Format 将为您将它们转换为字符串:

string result = string.Format("{0}_{1}", dtMRow("mcode"), dtRow("pcode"));

【讨论】:

    【解决方案4】:

    最佳性能:

    string resultString = dtMRow("mcode").ToString() + "_" + dtRow("pcode").ToString();
    

    等于:

    string resultString = string.Concat(dtMRow("mcode").ToString(), "_", dtRow("pcode").ToString());
    

    最佳视图但性能最差:

    string resultString = string.format("{0}_{1}", dtMRow("mcode").ToString(), dtRow("pcode").ToString());
    

    最差的视图和最差的性能:stringBuilder for little object

    ps:.ToString() 是多余的

    【讨论】:

      【解决方案5】:

      最好的方法是使用 System.Text.StringBuilder 的实例而不是字符串。在您的情况下,使用 ToString() 显式转换字符串:

      dtMRow("mcode").ToString() + "_" + dtRow("pcode").ToString()
      

      【讨论】:

        猜你喜欢
        • 2010-10-06
        • 2016-12-11
        • 2021-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多