加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 字符串数组加字符串不是错误,为什么?

发布时间:2020-12-16 00:24:00 所属栏目:百科 来源:网络整理
导读:我遇到了类似于以下代码: var a = (new string [] {}) + string.Empty; 我想问一下: 为什么这个代码可以编译(为什么不是这种类型的错误)? 如何理解这种行为? 解决方法 .NET Framework中有3个 + 运算符重载. 来自C#Spec $7.8.4 Addition operator string
我遇到了类似于以下代码:

var a = (new string [] {}) + string.Empty;

我想问一下:

>为什么这个代码可以编译(为什么不是这种类型的错误)?
>如何理解这种行为?

解决方法

.NET Framework中有3个 +运算符重载.

来自C#Spec $7.8.4 Addition operator

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

这就是你的var a =(new string [] {})string.Empty;匹配第三个重载.

并且(对象x,字符串y)使用String.Concat(object,object)重载,这是implemented之类的;

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 [] {}不是null,因为在MSIL中,它使用newarr及其文档;

The stack transitional behavior,in sequential order,is:

  1. The number of elements in the array is pushed onto the stack.
  2. The number of elements is popped from the stack and the array is created.
  3. An object reference to the new array is pushed onto the stack.

这就是它最后使用object.ToString()方法的原因.

从它的文件;

ToString is the major formatting method in the .NET Framework. It
converts an object to its string representation so that it is suitable
for display.The default implementation of the ToString method returns the fully
qualified name of the type

结果你的a将是System.String [].

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读