简体   繁体   中英

C# Invalidate automatic ToString conversion

In C#, I have a class:

public class Person
{
    public string name;
    public int id;
}

Currently, when I do:

Person person = new Person
{
    name = "John",
    id = 3
}
// Will be converted Console.Writeline("Person = " + person.ToString()); by the compiler
Console.Writeline("Person = " + person); 

What can I do in the class to invalidate the automatic conversion from person to person.ToString() and make the compiler give an error to indicate Person object cannot be converted to string implicitly?

What can I do in the class to invalidate the automatic conversion from person to person.ToString() and make the compiler give an error to indicate Person object cannot be converted to string implicitly?

You can't, at least not in an easy way. The overload of string + object will be the one emitting the ToString on object , which you have no way of controlling. This is specified in Addition Operator (7.7.4) part of the specification (emphasis mine):

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.

What you can do, which isn't a compile-time warning, is throw an exception from an overloaded ToString . I would definitely recommend not doing that . You could possibly write a Roslyn analyzer which looks for any object passed to Console.WriteLine without overriding the ToString method and emit a warning for that.

You'd have to write your programming language that doesn't have an overload of the + operator accepting a string and an object as its two operands. As it is, if you're using C# which states that such an operator overload is required as a part of the language specs , the code that you've shown must compile in C#. In order to make that operation not compile would require using a language that doesn't meet the C# language specs.

Using the new keyword when overriding the ToString method and marking it as obsolete looks to do the trick.

public class Person
{
    public string name;
    public int id;

    [Obsolete("this should not be used", true)]
    public new string ToString()
    {
        return null;
    }
}

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