根据互联网,当你这样做时
String someString = "" + object1 + object2 + object3;
ToString()
在每个对象上调用。
但这并没有发生!
这段代码:
String a = "a" + foo;
String b = "b" + foo.ToString();
Console.WriteLine(a);
Console.WriteLine(b);
Prints:
a
b("key":"foo")
这怎么可能?
我对整个项目进行了 Resharper 全面清理,它在某些地方破坏了代码,因为它删除了ToString()
在这样的字符串连接中!!损失了好几个小时..
Edit:这个问题发生在我正在使用的一个小型图书馆中。我无法提供非常短的单文件代码来重现这一点,但我已经使用这个库创建了一个小项目并上传到 github:
https://github.com/Vistritium/ToStringCSObjectConcat https://github.com/Vistritium/ToStringCSObjectConcat
https://github.com/Vistritium/ToStringCSObjectConcat/blob/master/TestString/Program.cs https://github.com/Vistritium/ToStringCSObjectConcat/blob/master/TestString/Program.cs
该库有 1178 行长。
如果您提供了隐式运算符 http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx将您的类转换为字符串,例如:
public class Foo
{
public string Key { get; set; }
public string Value { get; set; }
public static implicit operator string(Foo foo)
{
return foo == null ? string.Empty : foo.Value;
}
public override string ToString()
{
var str = string.Empty;
if (!string.IsNullOrEmpty(Key))
{
if (str.Length > 0)
str += ";";
str += ("Key=" + Key);
}
if (!string.IsNullOrEmpty(Value))
{
if (str.Length > 0)
str += ";";
str += ("Value=" + Value);
}
return str;
}
}
在这种情况下:
string a = "a" + new Foo { Key = "foo", Value = "" };
string b = "b" + new Foo { Key = "foo", Value = "" }.ToString();
Debug.WriteLine(a); // Prints "a".
Debug.WriteLine(b); // Prints "bKey=foo
如果你有的话,你也可以获得这种效果超载了+操作员 http://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx for string
and Foo
.
Update
根据 C# 语言规范,7.2.2 运算符重载 http://msdn.microsoft.com/en-us/library/aa691324%28v=vs.71%29.aspx:
所有一元和二元运算符都有预定义的实现,可在任何表达式中自动使用。除了预定义的实现之外,还可以通过在类和结构中包含运算符声明来引入用户定义的实现(第 10.9 节) http://msdn.microsoft.com/en-us/library/aa664461(v=vs.71).aspx。用户定义的运算符实现始终优先于预定义的运算符实现:仅当不存在适用的用户定义的运算符实现时,才会考虑预定义的运算符实现。
这就是为什么优先调用自定义逻辑而不是标准逻辑。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)