自动.ToString()?
我有一个这样的方法: void m1(string str)
并有一个这样的类:
public class MyClass
{
public bool b1 { set; get; }
//and other properties
}
现在为什么下面的代码不会导致编译错误?
IClass2 _class2 = new Class2();
MyClass c1 = new MyClass();
_class2.m1("abcdef" + c1);
当我调试它时,我意识到c1.ToString()
已被传递给m1
。为什么会发生这种自动 .ToString()
?我唯一能说的是m1已经在IClass2
接口中定义,并由Class2
实现。
I have a method like this: void m1(string str)
and have a class like this:
public class MyClass
{
public bool b1 { set; get; }
//and other properties
}
Now why following code does not cause compile error?
IClass2 _class2 = new Class2();
MyClass c1 = new MyClass();
_class2.m1("abcdef" + c1);
When I debug it, I realized that c1.ToString()
has been passed to m1
. Why this automatic .ToString()
has been occurred? The only thing I could say is that m1 has been defined in IClass2
interface and has been implemented by Class2
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这遵循 C# 语言规范中有关字符串连接的规则。请参阅 C# 4 规范的第 7.8.4 节(加法运算符)
如果您没想到会发生这种情况,请问您期望
"abcdef" + c1
表达式的结果是什么?请注意,
m1
、IClass2
和Class2
与此处发生的情况无关 - 只有串联表达式才是真正相关的:这就是触发调用的原因到ToString()
,无论该字符串稍后发生什么情况。This follows the rules of the C# language specification around string concatenation. See section 7.8.4 of the C# 4 spec (the addition operator)
If you didn't expect that to happen, may I ask what you expected the result of the
"abcdef" + c1
expression to be?Note that
m1
,IClass2
andClass2
are irrelevant to what's happening here - it's only the concatenation expression which is really relevant: that's what's triggering the call toToString()
, regardless of what's later happening to that string.编译器将
"abcdef" + c1
转换为string.Concat(object,object)
调用。这反过来会对每个参数调用.ToString()
并将它们连接起来。以下是来自 Reflector 的代码:请注意,最后一行涉及对
string.Concat(string, string)
的调用,其中发生真正的连接。The compiler turns
"abcdef" + c1
into astring.Concat(object,object)
call. This in turn will call.ToString()
on each of the arguments and concatenate them. Here's the code from reflector:Note that the last line involves a call to
string.Concat(string, string)
where the real concatenation happens.