Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

c# - Automatic .ToString()?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

String concatenation:

string operator +(string x, string y);
string operator +(string x, object y);
string operator +(object x, string y);

These overloads of the binary + operator perform string concatenation. If an operand of string concatenation isnull, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

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 and Class2 are irrelevant to what's happening here - it's only the concatenation expression which is really relevant: that's what's triggering the call to ToString(), regardless of what's later happening to that string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...