如何使用派生类中的用户定义的操作员明确施放对象

发布于 2025-02-10 21:30:06 字数 573 浏览 1 评论 0原文

考虑以下代码:

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情域 2025-02-17 21:30:06

虽然过载分辨率通常在编译时间发生,但将对象施放为Dynamic迫使其在运行时解决。

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) (dynamic) b)}");
  }

现在打印:

User-defined explicit cast B
The result is: 1

While overload resolution usually happens at compile time, casting the object to dynamic forces it to be resolved at runtime.

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) (dynamic) b)}");
  }

This now prints:

User-defined explicit cast B
The result is: 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文