这是我的第一篇文章,所以我对一些错误提前表示歉意,而且英语不是我的母语。 什么更好,为什么?请记住,我正在与另外 2 个人一起工作,我们将有 4 个类来代表不同类型的人,每个类将具有大约 15 个属性。
A - 为同一类中类的每个属性创建验证:
public class People
{
string name { get; set; }
private void ValidateName()
{
if(this.name.Contains("0", ..., "9"))
throw new Exception("Name can't contain numbers.");
}
}
或 B - 创建一个类(也许是静态类?)仅用于验证:
public class People
{
string name { get; set; }
}
static class Validation
{
static void Name(string name)
{
if(name.Contains("0", ..., "9"))
throw new Exception("Name can't contain numbers.")
}
}
//and then somewhere in the code I call the Validation.Name(name) to verify if the code is ok.
还有第三种更合适的选择吗?我什至不知道使用异常是否是正确的方法。
提前谢谢您!
最佳答案
您可以使用您的方法在构造函数中实例化时引发错误,如下所示
public class People
{
string name { get; set; }
public People(string n)
{
if (ValidateName(n))
{
this.name = n;
}
}
private bool ValidateName(string n)
{
char[] nums = "0123456789".ToCharArray();
if (n.IndexOfAny(nums) >= 0)
{
throw new Exception("Name can't contain numbers.");
}
return true;
}
}
使用上面的代码,下面的代码将抛出异常。
People p = new People("x1asdf");
这将是一个成功的实例化
People p = new People("xasdf");
关于c# - 在类验证代码中创建还是创建验证类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18337150/