[英]Is there a benefit to overloading the explicit operator if implicit has been overloaded in C#?
我正在使用一个结构,需要隐式运算符对字符串,并遇到一个我没有想过的基本问题。
public static implicit operator Version (string value) {...}
我可以理解只有显式运算符来强制执行转换,但如果隐式运算符已经过载,则无法想到需要它的情况。 有吗?
没有。 实际上,您无法为同一转换定义隐式显式转换运算符。 这是一个编译时错误:
public class Foo
{
public static implicit operator Foo(string value)
{
Console.WriteLine("implicit");
return null;
}
public static explicit operator Foo(string value)
{
Console.WriteLine("Explicit");
return null;
}
}
它给出了以下错误:
类型中重复的用户定义转换
...
如果你定义了一个隐式转换,你可以写出一个显式转换,它将使用隐式转换的代码来进行转换,但是没有办法为隐式转换和显式转换定义代码来执行不同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.