C# 在 setter 方法上添加验证 [英] C# add validation on a setter method

查看:17
本文介绍了C# 在 setter 方法上添加验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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 设置一个值,我应该通过一个正则表达式来实际设置,否则应该抛出异常.是否可以使用这种简短语法"进行构建,还是应该使用标准(如 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?

推荐答案

如果要在设置属性时进行验证,则需要使用非自动属性(即手动定义的 getset 方法).

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
}

这是我更喜欢的方法:

  1. 客户不应负责验证自己的数据,这是另一项责任 因此应该住在别处.
  2. 对于同一个域对象,不同的情况需要不同的验证逻辑.
  1. A Customer should not responsible for validating its own data, that is another responsibility and therefore should live elsewhere.
  2. Different situations call for different validation logic for the same domain object.

这篇关于C# 在 setter 方法上添加验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆