【发布时间】:2023-03-15 03:41:01
【问题描述】:
为什么我不能像这样同时定义隐式和显式运算符?
public class C
{
public static implicit operator string(C c)
{
return "implicit";
}
public static explicit operator string(C c)
{
return "explicit";
}
}
你可以做这个黑客:)
class Program
{
public class A
{
}
public class B
{
public static implicit operator A(B b)
{
Console.WriteLine("implicit");
return new A();
}
}
public class C : B
{
public static explicit operator A(C c)
{
Console.WriteLine("explicit");
return new A();
}
}
static void Main(string[] args)
{
C c = new C();
A a = c;
A b = (A) c;
}
}
打印出来:
implicit
explicit
【问题讨论】:
-
谁说你不能?即,当您尝试时会发生什么?
-
为什么要在两者之间实现不同的实现?
-
重写 ToString 甚至不接近隐式转换运算符。您的示例代码仅有效,因为 Console.WriteLine 具有对象重载并在对象上调用 ToString()。
-
它是为了好玩,我什至在那儿放了笑脸。
-
但是并没有达到预期的效果。如果没有显式强制转换,您不能将 C 作为字符串传递。接收代码将取决于为“隐式”运算符调用 ToString。