gpt4 book ai didi

c# - int 到 string 没有显式转换?

转载 作者:太空狗 更新时间:2023-10-29 20:44:50 24 4
gpt4 key购买 nike

我有一个简单的问题,但我很惊讶。

此代码有效:

int itemID = 1;
string dirPath = @"C:\" + itemID + @"\abc";

为什么我不必在这种情况下执行 itemID.ToString()

最佳答案

来自 MSDN

The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument 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.

根据其他答案中的一些评论,稍微扩展一下我的答案...

这个过程不仅仅是“语法糖”或便利。它是称为运算符重载的核心 C# 语言功能的结果。在 + 运算符和 String + 重载的情况下,提供重载作为抽象 String 类内部的一种方法,这是良好设计原则的核心基础。 + String 重载通过确保它永远不会返回空值来提供类型安全,而是为任何无法使用 .ToString() 方法转换的操作数返回空字符串。但是,即使自定义复杂类型(不仅仅是基元)也可以添加到字符串中,假设它们具有 .ToString() 重载,而 String 类型的实现不知道任何不同。

运算符重载是一种主要的语言特性,更多人应该学会利用它的力量。

关于c# - int 到 string 没有显式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18722516/

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