简体   繁体   English

将具体实现类型转换为通用接口类型

[英]Convert concrete implementation type to generic interface type

I have interfaces and implementations like this:我有这样的接口和实现:

public interface IRequest
{
   string Name{set;get;}
}

public class UppercaseRequest: IRequest
{
    public string Name{get; set}
}

public interface IHandler<T> where T: IRequest
{
   void Handle(T request);
}

public class UpperCaseHandler : IHandler<UpperCaseRequest>
{
     //implementation interface here
}

And a factory like this:还有这样的工厂:

public class HandlerFactory
{
    public IHandler<T> CreateHandler(T request) where T: IRequest
    {
       switch(request.Name)
       {
         case "UpperCase": return new UpperCaseHandler() as IHandler<T>;
                           //this line compile but always return null;
       }
    }
}

That handler method in HandlerFactory always returns null. HandlerFactory中的那个处理程序方法总是返回 null。 What am I doing wrong and how can I fix this behavior?我做错了什么,我该如何解决这种行为? Can you also give me some advice on how I can improve the code structure?您能否就如何改进代码结构给我一些建议?

Here is a modified and corrected code that works like a charm.这是一个修改和更正的代码,就像一个魅力。 We have the reference to an instance.我们有一个实例的引用。 But I don't know if it was you want...但不知道是不是你想要的...

The factory class should be static, isn't it?出厂的class应该是static吧?

在此处输入图像描述

static void Test()
{
  var a = new HandlerFactory().CreateHandler(new UpperCaseRequest() { Name = "UpperCase" });
}
public class HandlerFactory
{
  public IHandler<T> CreateHandler<T>(T request) where T : IRequest
  {
    switch ( request.Name )
    {
      case "UpperCase": return new UpperCaseHandler() as IHandler<T>;
    }
    return default(IHandler<T>);
  }
}

public interface IRequest
{
  string Name { set; get; }
}

public class UpperCaseRequest : IRequest
{
  public string Name { get; set; }
}

public interface IHandler<T> where T : IRequest
{
  void Handle(T request);
}

public class UpperCaseHandler : IHandler<UpperCaseRequest>
{
  public void Handle(UpperCaseRequest request)
  {
    throw new NotImplementedException();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM