自动的ToString()? [英] Automatic .ToString()?

查看:135
本文介绍了自动的ToString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的方法:无效M1(字符串str)键,有一类这样的:

 公共类MyClass的
{
    公共BOOL B1 {设置;得到; }

    //和其它性质
}
 

现在为什么下面code不会导致编译错误?

  IClass2 _class2 =新的Class2();
MyClass的C1 =新MyClass的();
_class2.m1(ABCDEF+ C1);
 

当我调试它,我意识到 c1.ToString()已传递到 M1 。为什么这种自动的ToString()已发生?我可以说的唯一的事情是,M1已经在 IClass2 定义的接口,并已通过类2 实施。

解决方案

在此之前,各地的字符串连接C#语言规范中的规则。看到C#4规范第7.8.4(加法运算符)

  

字符串连接:

 字符串操作符+(字符串x,y字符串);
字符串操作符+(字符串x,对象Y);
字符串操作符+(对象x,y字符串);
 

     

的二进制 + 运营商这些重载执行字符串连接。如果字符串连接的一个操作数是,一个空字符串代替。否则,任何非字符串参数都通过调用虚拟的ToString 方法继承类型的对象转换为它的字符串重新presentation。如果的ToString 返回,一个空字符串代替。

如果你不希望这样的事情发生,我可以问你期望的ABCDEF+ C1 EX pression得到的结果是<? / P>

注意 M1 IClass2 类2 是无关这里发生了什么 - 这仅仅是串联EX pression这是非常相关的:这是什么触发)调用的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.

解决方案

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.

这篇关于自动的ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆