简体   繁体   中英

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

In C#, what is the difference between this:

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.

Object.ToString supposed to return

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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