工厂模式返回 C# 中的泛型类型

man*_*iac 5 .net c# generics interface factory-pattern

public interface IRequestProcessor<out T>
{    
   T Translate(string caseId);
}

public class xyzReqProcessor : IRequestProcessor<xyzType>
{
  public xyzType Process(string xyzMsg)
  {
     return new xyz();
  }
}
public class VHDReqProcessor : IRequestProcessor<VHDType>
{
  public VHDType Process(string xyzMsg)
  {
     return new VHD();
  }
}
Run Code Online (Sandbox Code Playgroud)

到这里看起来不错。现在我想用工厂初始化类,但它无法返回 IRequestProcessor 类型的对象。

public static IRequestProcessor Get(FormType translatorType)
{

  IRequestProcessor retValue = null;
  switch (translatorType)
  {
    case EFormType.VHD:
      retValue = new VHDProcessor();
      break;
    case EFormType.XYZ: 
      retValue = new XYZProcessor();
      break;
  }
  if (retValue == null)
    throw new Exception("No Request processor found");

  return retValue;

}
Run Code Online (Sandbox Code Playgroud)

在调用 Factory.Get(FormTypetranslatorType) 方法时,我不想指定任何固定的对象类型,如下所示

Factory.Get<XYZType>(FormType 转换器类型)

Joh*_*nny 4

我不确定这个解决方案是否适合您的整体设计,但通过这个技巧您可以实现您所要求的。要点是有两个接口,一个是通用接口,另一个不是非通用接口将调用路由到通用接口。见下图:

public abstract class BaseType
{
    public abstract void Execute();
}

public class VhdType : BaseType
{
    public override void Execute()
    {
        Console.WriteLine("Vhd");
    }
}

public class XyzType : BaseType
{
    public override void Execute()
    {
        Console.WriteLine("Xyz");
    }
}

public interface IRequestProcessor
{
    BaseType Process();
}

public interface IRequestProcessor<T> : IRequestProcessor where T : BaseType, new()
{
    T Process<TInput>() where TInput : T;
}

public class VhdRequestProcessor : IRequestProcessor<VhdType>
{
    public BaseType Process()
    {
        return Process<VhdType>();
    }

    public VhdType Process<TInput>() where TInput : VhdType
    {
        return new VhdType();
    }
}

public class XyzRequestProcessor : IRequestProcessor<XyzType>
{
    public BaseType Process()
    {
        return Process<XyzType>();
    }

    public XyzType Process<TInput>() where TInput : XyzType
    {
        return new XyzType();
    }
}

public class RequestFactory
{
    public IRequestProcessor GetRequest(string requestType)
    {
        switch (requestType)
        {
            case "vhd": return new VhdRequestProcessor();
            case "xyz": return new XyzRequestProcessor();
        }

        throw new Exception("Invalid request");
    }            
}
Run Code Online (Sandbox Code Playgroud)

使用示例:

IRequestProcessor req = new RequestFactory().GetRequest("xyz");
BaseType r = req.Process();
r.Execute();
Run Code Online (Sandbox Code Playgroud)