我在阅读here有关在C#中创建不可变类的信息。有人建议我采用这种方式来实现真正的不变性:

private readonly int id;

public Person(int id) {

    this.id = id;
}

public int Id {
    get { return id; }
}


我了解这一点,但是如果我想进行一些错误检查,该如何抛出异常呢?给定以下课程,我只能考虑这样做:

private readonly int id;
private readonly string firstName;
private readonly string lastName;

public Person(int id,string firstName, string lastName)
{
    this.id=id = this.checkInt(id, "ID");
    this.firstName = this.checkString(firstName, "First Name");
    this.lastName = this.checkString(lastName,"Last Name");

}

private string checkString(string parameter,string name){

    if(String.IsNullOrWhiteSpace(parameter)){
        throw new ArgumentNullException("Must Include " + name);
    }

    return parameter;

}

private int checkInt(int parameter, string name)
{
    if(parameter < 0){

        throw new ArgumentOutOfRangeException("Must Include " + name);
    }
    return parameter;
}


那是正确的方法吗?如果没有,如何在不可变类中引发异常?

最佳答案

我将内联这两个私有方法:

  private readonly int id;
  private readonly string firstName;
  private readonly string lastName;

  public Person(int id, string firstName, string lastName)
  {
     if(String.IsNullOrWhiteSpace(firstName))
        throw new ArgumentNullException("firstName");
     if(String.IsNullOrWhiteSpace(lastName))
        throw new ArgumentNullException("lastName");
     if(id < 0)
        throw new ArgumentOutOfRangeException("id");


     this.id=id;
     this.firstName = firstName ;
     this.lastName = lastName ;
  }

09-06 06:29