gpt4 book ai didi

c# - 字符串数组加字符串不报错,为什么呢?

转载 作者:行者123 更新时间:2023-11-30 13:22:28 25 4
gpt4 key购买 nike

我遇到了类似下面的代码:

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

我想问:

  • 为什么这段代码可以通过编译(为什么不能通过类型错误)?
  • 如何理解这种行为?

最佳答案

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

来自 C# 规范 $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; 匹配第三个重载。

+ (object x, string 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());
}

并且由于 new 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[]

关于c# - 字符串数组加字符串不报错,为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22224483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com