首页 > 解决方案 > 如何投射 CreateDelegate 并分配给 Action

问题描述

我可以将采用 BaseClass 参数的方法分配给采用 SubClass 参数的 Action,但我不能使用 CreateDelegate 来做同样的事情。我需要它来将 SubClass 对象发送到同时采用 BaseClass 和 SubClass 参数的目标方法。

class Animal { }

class Cat : Animal { }

void Awake()
{
    Action<Cat> action = null;

    action += TestCat;
    action += TestAnimal;
    action += (Action<Cat>) Delegate.CreateDelegate( typeof( Action<Cat> ), this, "TestCat2" );

    // Casting error!
    action += (Action<Cat>) Delegate.CreateDelegate( typeof( Action<Animal> ), this, "TestAnimal2" );

    // Test
    action.Invoke( new Cat() );
}

void TestCat( Cat param ){ Debug.Log( "Cat" ); }

void TestAnimal( Animal param ) { Debug.Log( "Animal" ); }

void TestCat2( Cat param ){ Debug.Log( "Cat2" ); }

void TestAnimal2( Animal param ){ Debug.Log( "Animal2" ); }

“行动”的前三个任务工作正常。但是当我转换 CreateDelegate 的结果时,我得到了一个空指针。我错过了什么?

我为这个问题的糟糕标题道歉。如果您有改进,请分享。

标签: c#

解决方案


这是多播委托(链接)的限制,您可以使用操作包装器轻松解决:

public void Awake()
{
    Action<Cat> action = null;

    action += TestCat;
    action += TestAnimal;
    action += (Action<Cat>) Delegate.CreateDelegate( typeof( Action<Cat> ), this, "TestCat2" );

    action += new Action<Cat>
    ( 
        (Action<Cat>) Delegate.CreateDelegate( typeof( Action<Animal> ), this, "TestAnimal2" )
    );

    // Test
    action.Invoke( new Cat() );
}

小提琴


推荐阅读