委托不接受子类? [英] Delegate doesn't accept subclass?

查看:69
本文介绍了委托不接受子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代表似乎不接受子类,我认为这是最简单的例子。

My delegate doens't seem to accept a subclass, I think an example is the easiest.

public class A
{
     public A() { }
}

public class B : A
{
     public B() { }
}

public class Program
{
     private delegate void CallBack(A a);
     private static CallBack callBack = new CallBack(Test);

     public Main(string[] args)
     {
          callBack(new B());
     }

     private static void Test(A a)
     {
          Console.WriteLine("Test()");    
     }

     // Compilation error occurs if Test becomes:
     private static void Test(B a)
     {
          Console.WriteLine("Test()");
     }
 }

当我更改测试以接受 B 会引发编译错误。是不是很奇怪,因为 B 扩展了 A

When I change Test to accept B it throws a compilation error. Isn't this odd because B extends A?

编译器错误


测试匹配无重载

No overload for Test matches Callback

有没有办法让我的代表接受扩展 A 的类?

Is there a way to make my delegate accept a class that extends A?

推荐答案

这并不奇怪,因为如果您有扩展了 C 类的对象A ,如果只接受 B Test()没有任何意义$ c>。用于回调的任何方法都必须接受 any A ,而不仅仅是特定的子类。如果要 Test(,您需要更改回调委托签名以接受 B 。 )也接受 B

It isn't odd because if you have an object of class C that extends A, it wouldn't make sense to pass to Test() if it only accepts a B. Any method used for a Callback has to accept any A, not just a specific subclass. You would need to change the Callback delegate signature to accept B if you want to Test() to accept B as well.

class C : A {};

Callback callback = Test;

callback(new C()); //what if Test() accepted B???

这篇关于委托不接受子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆