gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:01:09 24 4
gpt4 key购买 nike

我正在阅读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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com