T - > IHandler< T> [英] Mapping between T --> IHandler<T>

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

问题描述

我有以下界面

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

我想要一个 HandlersManager class,将对象类型之间的映射保存到对应的处理程序中,但我不知道我应该如何定义保存此映射的对象。



例如,我想要的是:

  typeof(string) - > IHandler的实例< string> 
typeof(MyClass) - > IHandler< MyClass>实例

我到目前为止最好的东西是定义 Dictionary< Type,object> ; 用于映射,但在这种情况下,每次得到它时,我都必须将值转换为 IHandler 。 >

有没有更好的解决方案或者我完全错过的东西?

解决方案

这是一个很好的,只有一个通用的 IHandler< T> 界面。



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

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

然后你也可以定义一个泛型抽象基类,实现 IHandler< T> 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< Type,IHandler> ,您可以直接致电 IHandler.Handle 对您拉出的值:

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

另一方面,我们现在有一个额外的接口和一个抽象的基类只是为了隐藏用户代码,听起来不是非常令人印象深刻。


I have the following interface

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

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>

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?

解决方案

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);
}

Then you could also define a generic abstract base class that implements both IHandler<T> and 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);
    }
}

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);

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.

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

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