使用接口将泛型委托转换为另一种类型 [英] Casting generic delegates to another type with interfaces

查看:148
本文介绍了使用接口将泛型委托转换为另一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(使用.NET 4.0)
好​​的,所以我有

(Using .NET 4.0) Ok, so I have

private Dictionary<int, Action<IMyInterface, IMyInterface>> handler {get; set;}

public void Foo<T, U>(Action<T, U> myAction)
    where T : IMyInterface
    where U : IMyInterface
    {
        // | This line Fails
        // V
        Action<IMyInterface, IMyInterface> anotherAction = myAction;
        handler.Add(someInt, anotherAction);
    }

我正尝试将委托存储在通用集合中,因此我可以稍后将其拉出以调用它。
如何正确投射?

I'm trying to store the delegate in a generic collection, so I can pull it back out later to invoke it. How do I properly cast it?

推荐答案

Welp ...看起来像我,我的朋友发现了一些

Welp... looks like me and my friend found a bit of a work around.

public void Foo<T, U>(Action<T, U> myAction)
    where T : IMyInterface
    where U : IMyInterface
    {
        Action<IMyInterface, IMyInterface> anotherAction = (x, y) => eventHandler.Invoke((TSender)x, (TObject),y);
        handler.Add(someInt, anotherAction);
    }

通过简单的lambda包装,我们就能完成所需的工作。

With a simple lambda wrap, we accomplished what we needed.

这篇关于使用接口将泛型委托转换为另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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