1 + “2” 在 C# 中的工作原理

huangapple go评论72阅读模式
英文:

how 1 +"2" works in C#

问题

我正在阅读关于C#中的类型安全性,比如我们不能将整数值赋给布尔值等等,这让我进行了一些实验。

我执行了一段代码片段,希望它会在编译时产生错误,但它却正常工作并提供了一个结果。

var add = 1 + "2"; // 它在C#中返回了12作为结果

1 + “2” 在 C# 中的工作原理

如果我理解有误,请纠正我,并请分享任何简要解释此问题的文档链接。

英文:

I was reading about the type safety in C# like how we can't assign an integer value to a bool etc., which made me to do some experiment.

I executed a code snippet hoping that it will give a compile time error but it worked and provider a result.

var add = 1 + "2"; // it gave 12 as result in C#

1 + “2” 在 C# 中的工作原理

Please correct me if my understanding is incorrect and please share any document link explaining this in brief.

答案1

得分: 6

这段文字的翻译如下:

这个编译是因为已声明了一个+运算符,它以任何object作为第一个参数,以string作为第二个参数。

语言规范 表明:

预定义的加法运算符如下所示。对于数字和枚举类型,预定义的加法运算符计算两个操作数的和。当一个或两个操作数的类型为string时,预定义的加法运算符会连接操作数的字符串表示。
[...]
字符串连接:

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

二元+运算符的这些重载执行字符串连接。如果字符串连接的操作数为null,则会替换为空字符串。否则,任何非string操作数都将通过调用从类型object继承的虚拟ToString方法转换为其字符串表示形式。如果ToString返回null,则会替换为空字符串。

在你的情况下,运算符重载解析将选择上述列表中的第三个重载。它相当于1.ToString() + "2"

英文:

This compiles simply because there is a + operator declared, that takes any object as the first argument, and a string as the second argument.

The langauage specification says:

> The predefined addition operators are listed below. For numeric and enumeration types, the predefined addition operators compute the sum of the two operands. When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.
>
> [...]
>
> String concatenation:
>
> string operator +(string x, string y);
> string operator +(string x, object y);
> string operator +(object x, string y);
>
> These overloads of the binary + operator perform string concatenation. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string operand is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

In your case, operator overload resolution would select the third overload in the above list. It is equivalent to 1.ToString() + "2".

huangapple
  • 本文由 发表于 2023年5月13日 15:56:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定