string resultString = dtMRow("mcode") + "_" + dtRow("pcode")
当我执行上面的代码时,我希望将resultString
分配给类似"2356_ASDKJ"
的内容,但我得到以下异常:
从字符串“_”到“Double”类型的转换无效。
为什么编译器会尝试将"_"
转换为Double
?
将所有内容投射到strings
?
答案 0 :(得分:7)
因为dtMRow返回double?
最好的方法是
String.Format("{0}_{1}", dtMRow("mcode"), dtRow("pcode"));
答案 1 :(得分:1)
string resultString = string.format("{0}_{1}", dtMRow("mcode").ToString(), dtRow("pcode").ToString());
我会使用ToString()
来避免装箱操作。
答案 2 :(得分:1)
为什么编译器试图将“_”转换为Double?
因为dtMRow("mcode")
中的类型可能是doubles
。
String.Format会将它们转换为字符串:
string result = string.Format("{0}_{1}", dtMRow("mcode"), dtRow("pcode"));
答案 3 :(得分:1)
最佳表现:
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用于少数对象
p.s。:.ToString()
是多余的
答案 4 :(得分:-1)
最好的方法是使用System.Text.StringBuilder的实例而不是字符串。在您的情况下,使用ToString()显式转换任何字符串:
dtMRow("mcode").ToString() + "_" + dtRow("pcode").ToString()