且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

T - > IHandler< T>

更新时间:2022-10-24 20:19:48

这是一个很好的,只有一个通用的 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.