sách gpt4 ai đã đi

Tự động .ToString()?

In lại 作者:行者123 更新时间:2023-11-30 13:20:54 30 4
mua khóa gpt4 Nike

我有一个像这样的方法:void m1(string str) 并且有一个像这样的类:

public class MyClass
{
public bool b1 { set; get; }

//and other properties
}

为什么下面的代码不会导致编译错误?

IClass2 _class2 = new Class2();
MyClass c1 = new MyClass();
_class2.m1("abcdef" + c1);

当我调试它时,我意识到 c1.ToString() 已经传递给了 m1。为什么这个自动 .ToString() 已经发生了?我唯一能说的是,m1 已在 IClass2 接口(interface)中定义,并已由 Class2 实现。

1 Câu trả lời

这遵循有关字符串连接的 C# 语言规范的规则。请参阅 C# 4 规范的第 7.8.4 节(加法运算符)

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 isvô giá trị, 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 vô giá trị, an empty string is substituted.

如果您没想到会发生这种情况,请问您希望"abcdef"+ c1 表达式的结果是什么?

Xin lưu ý,m1,IClass2Class2 与此处发生的事情无关 - 只有连接表达式才是真正相关的:这就是触发对 ToString() 的调用,而不管该字符串后来发生了什么。

关于c# - 自动 .ToString()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3759343/

30 4 0
Bài viết được đề xuất: c# - 如何写入嵌入式资源?
Bài viết được đề xuất: Javascript 返回字符串到 Html
Bài viết được đề xuất: javascript - jquery 的 Instagram
Bài viết được đề xuất: C# 测试 null
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com