的ToString和字符串连接 - 意外的行为 [英] ToString and string concatenation - unexpected behavior
问题描述
据当你做互联网
String someString = "" + object1 + object2 + object3;
的ToString()
被称为在每个对象。
但是,这是不会发生!
这段代码:
But this is not happening! This code:
String a = "a" + foo;
String b = "b" + foo.ToString();
Console.WriteLine(a);
Console.WriteLine(b);
打印:
Prints:
a
b("key":"foo")
如何这可能吗?
我对整个项目进行了ReSharper的全面清理,并在一些地方分手的代码,因为它删除的ToString()
在这样的字符串连接!失去了很多时间。
I made Resharper full cleanup on whole project and it broke code in some place because it removed ToString()
in such string concat!! Lost many hours..
编辑:
在我使用小的某个库发生此问题。我不能提供很短的一个文件中的代码,将重现这一点,但我已经创建小的项目与此库,并上传至GitHub的:
This problem happened in one of small libraries I was using. I cannot provide very short one-file code that will reproduce this but I have created small project with this library and uploaded to github:
的 https://github.com/Vistritium/ToStringCSObjectConcat
的 https://github.com/Vistritium/ToStringCSObjectConcat/blob/master/TestString/Program.cs
图书馆是1178行代码。
The library is 1178 lines long.
推荐答案
这可以,如果你提供了一个的隐运营商类转换成字符串,例如:
This can happen if you have provided an implicit operator converting your class to a string, for instance:
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
您还可以,如果你有的超载 +
为字符串
和富
。
You could also get this effect if you have overloaded the +
operator for string
and Foo
.
> 更新
从C#语言规范的 7.2.2操作符重载:
所有一元和二元运算符具有预定义的实现,都自动在任何表达式提供除了预定义实现,用户自定义的实现可以通过包括类和结构的(第10.9节)用户定义的运营商实现始终接管预定义运算符的优先级实现:只当存在将预定义的运算符实现被认为是不适用的用户定义运算符实现。
All unary and binary operators have predefined implementations that are automatically available in any expression. In addition to the predefined implementations, user-defined implementations can be introduced by including operator declarations in classes and structs (Section 10.9). User-defined operator implementations always take precedence over predefined operator implementations: Only when no applicable user-defined operator implementations exist will the predefined operator implementations be considered.
这就是为什么自定义逻辑被优先调用,标准的逻辑。
That's why the custom logic gets invoked in preference to the standard logic.
这篇关于的ToString和字符串连接 - 意外的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!