【问题标题】:How to create generic method which return instance of generic?如何创建返回泛型实例的泛型方法?
【发布时间】:2012-05-05 12:37:34
【问题描述】:

我想创建一个简单的工厂类来实现这样的接口:

IFactory 
{
   TEntity CreateEmpty<TEntity>(); 
}

在这个方法中,我想返回一个 TEntity 类型(泛型)的实例。 示例:

TestClass test = new Factory().CreateEmpty<TestClass>(); 

有可能吗?界面是否正确?

我尝试过这样的事情:

private TEntity CreateEmpty<TEntity>() {
   var type = typeof(TEntity);
   if(type.Name =="TestClass") {
      return new TestClass();
   }
   else {
     ...
   }
}

但它不能编译。

【问题讨论】:

    标签: c# generics methods


    【解决方案1】:

    你需要在泛型类型参数上指定new()约束

    public TEntity CreateEmpty<TEntity>() 
        where TEntity : new()
    {
        return new TEntity();
    }
    

    新的约束规定所使用的具体类型必须有一个公共的默认构造函数,即没有参数的构造函数。

    public TestClass
    {
        public TestClass ()
        {
        }
    
        ...
    }
    

    如果你根本不指定任何构造函数,那么该类将默认有一个公共的默认构造函数。

    您不能在new() 约束中声明参数。如果您需要传递参数,则必须为此目的声明一个专用方法,例如通过定义适当的接口

    public interface IInitializeWithInt
    {
         void Initialize(int i);
    }
    
    public TestClass : IInitializeWithInt
    {
         private int _i;
    
         public void Initialize(int i)
         {
             _i = i;
         }
    
         ...
    }
    

    在你的工厂

    public TEntity CreateEmpty<TEntity>() 
        where TEntity : IInitializeWithInt, new()
    {
        TEntity obj = new TEntity();
        obj.Initialize(1);
        return obj;
    }
    

    【讨论】:

    • 感谢您的全面回答。
    【解决方案2】:
    interface IFactory<TEntity> where T : new()
    {
       TEntity CreateEmpty<TEntity>(); 
    }
    

    【讨论】:

      【解决方案3】:

      此方法将帮助您,按顺序传递参数,它们在构造函数中的顺序:

      private T CreateInstance<T>(params object[] parameters)
      {
          var type = typeof(T);
      
          return (T)Activator.CreateInstance(type, parameters);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-19
        • 1970-01-01
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多