我对验证有疑问。假设我有超过1个类,我想以下列方式进行验证 -
class1 - 第一属性应该是强制性的 class2 - 第二属性应该是强制性的 class3 - 第一属性应该是强制性的
所以我可以写一些常见的东西,这样我就不应该为三个类编写类似null检查的代码。我的意思是我不想重复3个不同类的空检查。应该有一些常见的,如果我传递实例并进行验证。我能做到吗?
答案 0 :(得分:0)
我会选择这样的模型
namespace ConsoleApplication {
internal class Program {
private static void Main(string[] args) {
Person p1 = new Person();
p1.Validate(); // Exception
Person p2 = new Person{Name = "Jack"};
p2.Validate(); // OK
Employee e1 = new Employee();
e1.Validate(); // Exception
Employee e2 = new Employee {Name = "John"};
e2.Validate(); // Exception
Employee e3 = new Employee { EmployeeNumber = 127};
e3.Validate(); // Exception
Employee e4 = new Employee {
Name = "Gill",
EmployeeNumber = 127
};
e4.Validate(); // OK
}
}
public class Person {
public string Name { get; set; }
public virtual void Validate() {
if (string.IsNullOrEmpty(Name)) {
throw new NotSupportedException("Name is not set");
}
}
}
public class Employee : Person {
public int EmployeeNumber { get; set; }
public override void Validate() {
base.Validate();
if (EmployeeNumber <= 0) {
throw new NotSupportedException("EmployeeNumber is not set");
}
}
}
}