简体   繁体   English

重写ToString和在C#中使用隐式/显式转换运算符有什么区别?

[英]What is the difference between overriding ToString and using implicit/explicit conversion operators in C#?

In C#, what is the difference between this: 在C#中,这之间有什么区别:

public override string ToString()
{
    return "Person: " + Name;
}

And this: 和这个:

public static implicit/explicit operator string(Person person)
{
    return "Person: " + Name;
}

Semantics is somewhat different. 语义有些不同。

Conversion operators say " convert to string (or another) type ": 转换运算符说“ 转换为字符串(或其他)类型 ”:

C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types. C#使程序员可以在类或结构上声明转换,以便可以将类或结构与其他类或结构或基本类型进行相互转换。

Object.ToString supposed to return Object.ToString应该返回

A string that represents the current object. 代表当前对象的字符串。

meaning " give me (usually human) readable text representation of the object ". 意思是“ 给我(通常是人类)对象的可读文本表示形式 ”。

(I'm not saying though that such semantics is always respected. Eg sometimes you may see ToString and FromString are used as conversion functions.) (我并不是说始终会尊重此类语义。例如,有时您可能会看到ToStringFromString被用作转换函数。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM