英文:
how 1 +"2" works in C#
问题
我正在阅读关于C#中的类型安全性,比如我们不能将整数值赋给布尔值等等,这让我进行了一些实验。
我执行了一段代码片段,希望它会在编译时产生错误,但它却正常工作并提供了一个结果。
var add = 1 + "2"; // 它在C#中返回了12作为结果
如果我理解有误,请纠正我,并请分享任何简要解释此问题的文档链接。
英文:
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#
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"
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论