c# - 如何投射 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 的结果时,我得到了一个空指针。我错过了什么?
我为这个问题的糟糕标题道歉。如果您有改进,请分享。
解决方案
这是多播委托(链接)的限制,您可以使用操作包装器轻松解决:
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() );
}
推荐阅读
- vaadin - Vaadin 10,如何将 css 类添加到 Java 中的 div 元素?
- python - 视频的获取状态与其在 if 函数中输入的字符串值不匹配
- javascript - HTML onsubmit 事件不返回元素
- java-web-start - Java WebStart 自定义安全策略被忽略
- knex.js - 如何获取 knex.js 中所有数据库的列表?
- php - 使用 PHP foreach 将类添加到 div
- ionic-framework - Calendar-PhoneGap-Plugin 创建事件,然后将其删除
- database - 如果列不存在,则在插入时添加列
- ios - 无法让 JSON Structs 工作 Swift 4
- java - Sqlite 数据库打不开