📜  其中 T : class, new() - 任何代码示例

📅  最后修改于: 2022-03-11 14:57:53.697000             🧑  作者: Mango

代码示例1
public void MakeCars()
{
    //This won't compile as researchEngine doesn't have a public constructor and so can't be instantiated.
    CarFactory researchLine = new CarFactory();
    var researchEngine = researchLine.MakeEngine();

    //Can instantiate new object of class with default public constructor
    CarFactory productionLine = new CarFactory();
    var productionEngine = productionLine.MakeEngine();
}

public class ProductionEngine { }
public class ResearchEngine
{
    private ResearchEngine() { }
}

public class CarFactory where TEngine : class, new()
{
    public TEngine MakeEngine()
    {
        return new TEngine();
    }
}