小编man*_*iac的帖子

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

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 …
Run Code Online (Sandbox Code Playgroud)

.net c# generics interface factory-pattern

5
推荐指数
1
解决办法
4520
查看次数

标签 统计

.net ×1

c# ×1

factory-pattern ×1

generics ×1

interface ×1