牛逼之间的映射 - > IHandler< T> [英] Mapping between T --> IHandler<T>

查看:191
本文介绍了牛逼之间的映射 - > IHandler< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下接口

public interface IHandler<T>
{
    Handle(T myObject);
}

我想有一个 HandlersManager 类持有对象类型之间的映射到其相应的处理程序,但我不知道怎么我应该定义持有这种映射的对象。

I'd like to have a HandlersManager class with holds a mapping between object types to their corresponding handler, but I'm not sure how I'm supposed to define the object that hold this mapping.

例如,我想有是这样的:

For example, what I'd like to have is this:

typeof(string)  --> instance of IHandler<string>
typeof(MyClass) --> instance of IHandler<MyClass>

我有这么的最好的事情远是定义词典&LT;类型,对象&gt; 的映射,但在这种情况下,我将不得不值转换为 IHandler&LT; T&GT; 每次我得到它的时候

The best thing I got so far was to define Dictionary<Type, object> for the mapping, but in this case I would have to cast the value to IHandler<T> every time I get it.

有没有更好的解决方案或东西,我已经完全错过了?

Is there a better solution or something that I have completely missed?

推荐答案

这是好,因为它可以得到的只是一个普通的 IHandler&LT; T&GT; 接口

That's as good as it can get with only a generic IHandler<T> interface.

为了探索更多的选择,我们可以定义界面的非通用版本:

In order to explore more options, we could define a non-generic version of the interface:

public interface IHandler
{
    void Handler(object myObject);
}

然后,你还可以定义实现了一个通用的抽象基类既 IHandler&LT; T&GT; IHandler

public abstract class BaseHandler<T> : IHandler, IHandler<T>
{
    public abstract void Handle(T myObject);

    void IHandler.Handle(object myObject)
    {
        ((IHandler<T>)this).Handle((T) myObject);
    }
}

在这一点上,你可以有一个的IDictionary&LT;类型,IHandler&GT; 键,可以直接调用 IHandler.Handle 在值你拉出来的:

At this point you can have an IDictionary<Type, IHandler> and you can directly call IHandler.Handle on the values you pull out of it:

var obj = /* whatever */
dictionary[obj.GetType()].Handle(obj);

在另一方面,我们现在有一个额外的接口和抽象基类,只是为了掩盖从用户code,这听起来并不很IM pressive一个演员。

On the other hand we now have an additional interface and an abstract base class just to hide a cast from "user" code, which doesn't sound very impressive.

这篇关于牛逼之间的映射 - &GT; IHandler&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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