Rom*_*nov 0 c# tostring implicit-conversion
在C#中,我有一个类:
public class Person
{
public string name;
public int id;
}
Run Code Online (Sandbox Code Playgroud)
目前,当我这样做时:
Person person = new Person
{
name = "John",
id = 3
}
// Will be converted Console.Writeline("Person = " + person.ToString()); by the compiler
Console.Writeline("Person = " + person);
Run Code Online (Sandbox Code Playgroud)
我可以在类中做什么来使从人到人的自动转换无效.ToString()并使编译器给出一个错误来指示Person对象不能隐式转换为字符串?
我可以在类中做什么来使从人到人的自动转换无效.ToString()并使编译器给出一个错误来指示Person对象不能隐式转换为字符串?
你不能,至少不是一个简单的方法.string+ 的重载object将是发出ToStringon的object那个,你无法控制.这在规范的附加算子(7.7.4)部分中指定(强调我的):
当一个或两个操作数的类型为字符串时,binary +运算符执行字符串连接.如果字符串连接的操作数为null,则替换空字符串.否则,通过调用从类型对象继承的虚拟ToString方法,将任何非字符串参数转换为其字符串表示形式.如果ToString返回null,则替换空字符串.
你可以做的,不是编译时警告,是从重载中抛出异常ToString.我肯定会建议不这样做.您可以编写一个Roslyn分析器,它可以查找传递给它的任何对象,Console.WriteLine而不会覆盖该ToString方法并发出警告.