如果BaseFruit有一个构造函数接受int权重,我可以实例化一个水果在一个泛型方法像这样?

public void AddFruit<T>()where T: BaseFruit{
    BaseFruit fruit = new T(weight); /*new Apple(150);*/
    fruit.Enlist(fruitManager);
}

注释后面添加了一个示例。似乎只有给BaseFruit一个无参数的构造函数,然后通过成员变量填充所有内容,才能做到这一点。在我的实际代码中(不是关于水果),这是相当不切实际的。

- update - 所以它似乎不能用任何约束条件来解决。从答案中可以得出三个备选方案:

工厂模式 反射 激活剂

我倾向于认为反射是最不干净的一种,但我无法在另外两种之间做出决定。


当前回答

你可以使用反射:

public void AddFruit<T>()where T: BaseFruit
{
  ConstructorInfo constructor = typeof(T).GetConstructor(new Type[] { typeof(int) });
  if (constructor == null)
  {
    throw new InvalidOperationException("Type " + typeof(T).Name + " does not contain an appropriate constructor");
  }
  BaseFruit fruit = constructor.Invoke(new object[] { (int)150 }) as BaseFruit;
  fruit.Enlist(fruitManager);
}

编辑:增加了构造函数== null检查。

编辑:一个更快的变种使用缓存:

public void AddFruit<T>()where T: BaseFruit
{
  var constructor = FruitCompany<T>.constructor;
  if (constructor == null)
  {
    throw new InvalidOperationException("Type " + typeof(T).Name + " does not contain an appropriate constructor");
  }
  var fruit = constructor.Invoke(new object[] { (int)150 }) as BaseFruit;
  fruit.Enlist(fruitManager);
}
private static class FruitCompany<T>
{
  public static readonly ConstructorInfo constructor = typeof(T).GetConstructor(new Type[] { typeof(int) });
}

其他回答

你可以使用反射:

public void AddFruit<T>()where T: BaseFruit
{
  ConstructorInfo constructor = typeof(T).GetConstructor(new Type[] { typeof(int) });
  if (constructor == null)
  {
    throw new InvalidOperationException("Type " + typeof(T).Name + " does not contain an appropriate constructor");
  }
  BaseFruit fruit = constructor.Invoke(new object[] { (int)150 }) as BaseFruit;
  fruit.Enlist(fruitManager);
}

编辑:增加了构造函数== null检查。

编辑:一个更快的变种使用缓存:

public void AddFruit<T>()where T: BaseFruit
{
  var constructor = FruitCompany<T>.constructor;
  if (constructor == null)
  {
    throw new InvalidOperationException("Type " + typeof(T).Name + " does not contain an appropriate constructor");
  }
  var fruit = constructor.Invoke(new object[] { (int)150 }) as BaseFruit;
  fruit.Enlist(fruitManager);
}
private static class FruitCompany<T>
{
  public static readonly ConstructorInfo constructor = typeof(T).GetConstructor(new Type[] { typeof(int) });
}

可以使用如下命令:

 T instance = (T)typeof(T).GetConstructor(new Type[0]).Invoke(new object[0]);

一定要看到下面的内容 参考。

是的,改变你的位置:

where T:BaseFruit, new()

但是,这只适用于无参数构造函数。您必须使用其他方法来设置属性(设置属性本身或类似的东西)。

最简单的解决方案 Activator.CreateInstance T < > ()

你不能使用任何参数化构造函数。如果有“where T: new()”约束,则可以使用无参数构造函数。

这很痛苦,但生活就是这样。

这是我想用“静态接口”解决的问题之一。然后可以约束T以包含静态方法、操作符和构造函数,然后调用它们。