如果我尝试执行从double到int的隐式转换,我会得到 *编辑器中的警告 *编译错误
如何为自定义类型的运算符实现此行为?
public struct A
{
private readonly double value;
public A(double value)
{
this.value = value;
}
// NOTE I want this operation to be prohibited
public static A operator +(A a, B b)
{
throw new InvalidOperationException();
}
public static implicit operator double(A a)
{
return a.value;
}
public static implicit operator A(double value)
{
return new A(value);
}
}
public struct B
{
private readonly double value;
public B(double value)
{
this.value = value;
}
public static implicit operator double(B b)
{
return b.value;
}
public static implicit operator B(double value)
{
return new B(value);
}
}
public class Example
{
public void Method()
{
A a = 0.0d;
B b = 0.0d;
// QUESTION is there any way to show custom editor errors and/or make compilation fail?
A result = a + b;
}
}
您可以在示例中看到,如果值类型A和B是加法操作数,则抛出异常。
我想显示编辑器警告和/或使编译失败。有什么办法可以实现这种行为?
答案 0 :(得分:5)
这是编译器的默认行为,如果不进行转换并且您无需执行任何操作。
但是要进行转换,您需要重载运算符(来自here的示例)。
public static explicit operator Celsius(Fahrenheit fahr)
{
return new Celsius((5.0f / 9.0f) * (fahr.Degrees - 32));
}
您还可以重载其他运算符(来自here的示例):
public static Fraction operator +(Fraction a, Fraction b)
{
return new Fraction(a.num * b.den + b.num * a.den,
a.den * b.den);
}
答案 1 :(得分:1)