字符串=字符串+ INT:什么是幕后? [英] string = string + int: What's behind the scenes?

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

问题描述

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

 字符串某物=东西+ 0;

我的问题是:


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

     字符串某物= 0; //错误:无法转换的源类型'诠释'为目标类型'字符串'


  2. C#如何铸就0作为字符串。它是 0.ToString()(串)0 或其他什么东西?


  3. 如何找到previous问题的答案吗?


解决方案

它编译成一个呼叫 String.Concat(对象,对象) ,像这样的:

 字符串某物= String.Concat(东西,0);

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

这方法被定义如下:(从.NET参考源获取)

 公共静态字符串连接(对象为arg0,ARG1对象){
        如果(arg0中== NULL){
            将arg0 =的String.Empty;
        }        如果(ARG1 == NULL){
            ARG1 =的String.Empty;
        }
        返回的毗连(arg0.ToString(),arg1.ToString());
    }

(这要求 String.Concat(字符串,字符串)


要发现这种情况,可以使用反汇编,或反思(IL或C#中,没有优化),看看 + 行编译成。

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

string sth = "something" + 0;

My questions are:

  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'
    

  2. How C# casts 0 as string. Is it 0.ToString() or (string)0 or something else?

  3. How to find an answer of the previous question?

解决方案

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)

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());
    }

(This calls String.Concat(string, string))


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

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

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