如果达到特定条件,如何使构造函数产生null?

时间:2019-03-04 06:23:20

标签: c#

出于学术目的,我提供以下示例。无条件创建Exercise实例作为属性将在运行时触发溢出。因此,我必须检查ctor中实例的数量。我认为有很多方法可以做到,但在这里我只想关注ctor。

问题

如果null是否可以使构造函数产生counter>9?如果是,该怎么办?

class Exercise
{
    Exercise e = new Exercise();
    static int counter = 0;
    public Exercise()
    {
        //if (++counter > 9)
        // return null;
    }

    static void Main()
    {
        Exercise e = new Exercise();
    }
}

2 个答案:

答案 0 :(得分:4)

不能。构造函数应始终创建一个有效的对象,并且该语言尝试通过不允许您从构造函数返回null来强制实施此对象。您可以使用factory pattern并封装对象的创建。

public class ExerciseFactory {
  static int counter = 0;


  public static GetExercise() {
    if (counter > 9) return null;
    counter++
    return new Exercise();
  }

}

答案 1 :(得分:2)

您可以使用工厂方法来实现。以下示例在LinqPad中运行,因此是Dump()方法。您必须将它替换为Console.WriteLine或其他适合您的输出方法:

void Main()
{
    var exerciseList = new List<Exercise>();
    for (int i = 0; i < 20; i++)
    {
        Exercise e = Exercise.Create();
        exerciseList.Add(e);            
    }
    exerciseList.Count(x => x != null).Dump();
}

public class Exercise
{
    private static int _counter = 0;
    private Exercise()
    {
    }

    public static Exercise Create() 
    {
        if (_counter > 8)
        {
            //or throw exception?
            return null;
        }
        else {
            _counter++;
            return new Exercise();

        }
    }
}

这里要注意的一件事是,构造函数是私有的,因此没有人可以仅通过不调用Create来规避该限制。这样,您将无法使用new关键字来新建实例。