如何使用派生类中的用户定义的操作员明确施放对象
考虑以下代码:
class A {
public static explicit operator int(A a) {
Console.WriteLine("User-defined explicit cast A");
return 42;
}
}
class B : A {
public static explicit operator int(B a) {
Console.WriteLine("User-defined explicit cast B");
return 1;
}
}
public void TestCast() {
A b = new B();
Console.WriteLine($"The result is: {(int) b)}");
}
此打印:
User-defined explicit cast A
The result is: 42
我有没有办法在运行时使用实例类型的用户定义的铸造运算符,而不知道实例类型在编译时实际是什么?
Consider the following code:
class A {
public static explicit operator int(A a) {
Console.WriteLine("User-defined explicit cast A");
return 42;
}
}
class B : A {
public static explicit operator int(B a) {
Console.WriteLine("User-defined explicit cast B");
return 1;
}
}
public void TestCast() {
A b = new B();
Console.WriteLine(quot;The result is: {(int) b)}");
}
This prints:
User-defined explicit cast A
The result is: 42
Is there a way for me to cast using the instance's type's user-defined cast operator at runtime, without knowing what the instance type actually is at compile time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然过载分辨率通常在编译时间发生,但将对象施放为
Dynamic
迫使其在运行时解决。现在打印:
While overload resolution usually happens at compile time, casting the object to
dynamic
forces it to be resolved at runtime.This now prints: