日期:2014-05-17  浏览次数:20872 次

怎么从语义上理解“几乎任何对象都能与string相加并自动调用ToString()”
可能调用ToString只是表面现象,但实验结果是如此

在object和string中都没找到对运算符“+”的重写,也没有相关的implicit explicit的定义,怎么从主义上理解这样的用法呢?


            string a = "abc";
            Type b = a.GetType();
            string c = a + b;
            string d = b + a;

------解决方案--------------------
所有继承与object的都会实现tostring方法,与字符串做+操作,编译器会自动调用tostring方法,这个+号不是相加,而是合并。
------解决方案--------------------
重载+号是提供给你的一种方法而已,.NET内置好的一些重载你是看不到的,这里的转换都是内置的,不会写在类型定义上面。
------解决方案--------------------
string c = a + b;

相关IL代码如下:

IL_0018:  call    string [mscorlib]System.String::Concat(object,
                                                              object)


发现,编译后,是调用String对象的Concat方法,

然后反编译查看Concat方法的代码,相关代码如下:

public static String Concat(params Object[] args) {
            if (args==null) {
                throw new ArgumentNullException("args"); 
            }
            Contract.Ensures(Contract.Result<String>() != null); 
            Contract.EndContractBlock(); 

            String[] sArgs = new String[args.Length]; 
            int totalLength=0;

            for (int i=0; i<args.Length; i++) {
                object value = args[i]; 
                sArgs[i] = ((value==null)?(String.Empty):(value.ToString()));
                if (sArgs[i] == null) sArgs[i] = String.Empty; // value.ToString() above could have returned null 
                totalLength += sArgs[i].Length; 
                // check for overflow
                if (totalLength < 0) { 
                &nb