C# 在不可变类中引发异常

标签 c# class exception immutability

我正在阅读here关于在 C# 中创建不可变类。有人建议我以这种方式创建我的类以获得真正的不变性:

private readonly int id;

public Person(int id) {

    this.id = id;
}

public int Id {
    get { return id; }
}

我明白了,但是如果我想做一些错误检查,我该如何抛出异常呢?鉴于以下类(class),我只能想到这样做:

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)方法:

  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 ;
  }

关于C# 在不可变类中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31313343/

相关文章:

c# - 如何递归返回直接对象中 'toy' 项目的数量以及该对象的所有直接子对象

c# - 使用 itextsharp 将 html 生成为 pdf

c# - 寻找不存在的列

Java swing 添加来自另一个类的组件

c# - 使用 AAD 作为身份提供程序从 Azure 函数应用程序中的 token 检索角色

java - 初始化类对象

c++ - 正确设置基类和派生类之间的函数返回

java - 如何避免打印异常并在遇到异常时分配另一个操作?我的尝试不成功

ios - objective-C : unrecognized selector sent to instance 0xba3e750

Android 无法暂停 Activity 接收器未注册