string = string + int:后台是什么? [英] string = string + int: What's behind the scenes?

查看:186
本文介绍了string = string + int:后台是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,您可以隐式连接一个字符串,让我们说,一个整数:

In C# you can implicitly concatenate a string and let's say, an integer:

string sth = "something" + 0;

我的问题是:


  1. 为什么,通过假设你可以隐式连接一个字符串和一个int的事实,C#不允许初始化字符串,如下:

  1. Why, by assuming the fact that you can implicitly concatenate a string and an int, C# disallows initializing strings like this:

string sth = 0; // Error: Cannot convert source type 'int' to target type 'string'


  • C#转换为字符串0。是 0.ToString()还是(string)0 还是其他?


    推荐答案

    它编译为调用 String.Concat(object,对象) ,像这样:

    It compiles to a call to String.Concat(object, object), like this:

    string sth = String.Concat("something", 0);
    

    (注意,这个特定的行实际上会被编译器优化)

    (Note that this particular line will actually be optimized away by the compiler)

    此方法定义如下:(取自.Net参考资料来源)

    This method is defined as follows: (Taken from the .Net Reference Source)

        public static String Concat(Object arg0, Object arg1) {
            if (arg0==null) {
                arg0 = String.Empty; 
            }
    
            if (arg1==null) { 
                arg1 = String.Empty;
            } 
            return Concat(arg0.ToString(), arg1.ToString());
        }
    

    (这会调用 String.Concat )

    要发现这一点,您可以使用 ildasm ,或者Reflector(在IL中或没有优化的C#中)来查看 + 行编译的内容。

    To discover this, you can use ildasm, or Reflector (in IL or in C# with no optimizations) to see what the + line compiles to.

    这篇关于string = string + int:后台是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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