如果在C#中隐式重载,重载显式运算符是否有好处?

Rah*_*han 3 .net c# operator-overloading implicit-conversion explicit-conversion

我正在使用一个结构,需要隐式运算符对字符串,并遇到一个我没有想过的基本问题.

public static implicit operator Version (string value) {...}
Run Code Online (Sandbox Code Playgroud)

我可以理解只有显式运算符来强制执行转换,但如果隐式运算符已经过载,则无法想到需要它的情况.有吗?

Ser*_*rvy 8

没有.实际上,您无法为同一转换定义隐式显式转换运算符.这是一个编译时错误:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

它给出了以下错误:

类型中重复的用户定义转换 ...

如果你定义了一个隐式转换,你可以写出一个显式转换,它将使用隐式转换的代码来进行转换,但是没有办法为隐式转换和显式转换定义代码来执行不同的操作.