C#中的setter方法添加验证 [英] C# add validation on a setter method
问题描述
我有几个变量,我在C#中定义:
I have a a couple of variables that i define in C# by:
public String firstName { get; set; }
public String lastName { get; set; }
public String organization { get; set; }
我要的是,当你尝试设置的值添加验证这些方法。比方说,你要设置的firstName的值时,我应该通过thrue一个正则表达式来actuelly进行设置,否则异常应被抛出。这是不可能建立这种短语法,或者我应该(在JAVA等)的getter和setter方法去规范,并在那里验证数据?
What i want is to add validation to these methods when you try to set a value. Lets say your going to set a value for firstName, the i should pass thrue a regexp to actuelly be set, otherwise an exception should be thrown. Is this possible to build with this "short syntax" or should I go for standard (like in JAVA) getters and setters and in there validate the data?
推荐答案
如果您希望在属性设置为验证,就需要使用非自动属性(即手动定义 GET
和设置
方法)。
If you want to validate when the property is set, you need to use non-auto properties (i.e., manually defined get
and set
methods).
但另一种方式来验证是有验证逻辑从域对象分开。
But another way to validate is to have the validation logic separate from the domain object.
class Customer {
public string FirstName { get; set; }
public string LastName { get; set; }
public string Organization { get; set; }
}
interface IValidator<T> {
bool Validate(T t);
}
class CustomerValidator : IValidator<Customer> {
public bool Validate(Customer t) {
// validation logic
}
}
然后,你可以说:
Customer customer = // populate customer
var validator = new CustomerValidator();
if(!validator.Validate(customer)) {
// head splode
}
这是我比较喜欢的方式:
This is the approach I prefer:
- A
客户
不应该负责验证自己的数据,那就是另一责任,因此应该在其他地方居住。 - 不同情况,要求对同一领域对象不同的验证逻辑。
- A
Customer
should not responsible for validating its own data, that is another responsibility and therefore should live elsewhere. - Different situations call for different validation logic for the same domain object.
这篇关于C#中的setter方法添加验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!