简体   繁体   English

C#自定义对象验证设计

[英]C# Custom Object Validation Design

I currently have to validate custom Field Objects for my application. 目前,我必须为我的应用程序验证自定义字段对象。 Simply put, each Field object consists of information about the validation for the field, as well as the value of the field. 简而言之,每个Field对象都包含有关该字段的验证以及该字段的值的信息。 I am validating fields in bulk, so currently, I have a validation class, that has a method for each validation. 我正在批量验证字段,因此目前,我有一个验证类,该类具有用于每个验证的方法。 For required fields, it looks something like this: 对于必填字段,它看起来像这样:

      private void RequiredFields()
      {
            foreach (Field field in allFields)
            {
                if ((field.Required == true) && (field.Value == string.Empty))
                {
                    field.isValid = false;
                }
            }
      }

Now my problem is that I feel like I should a layer of abstraction to the validation, so instead of saying: 现在我的问题是,我觉得我应该对验证进行抽象,所以不要说:

if ((field.Required == true) && (field.Value == string.Empty))

... I would add a validation class, to accept the values and turn it into this: ...我将添加一个验证类,以接受值并将其转换为:

if (!validater.RequiredFields(field.Required, field.Value))

If I were to do this, it would allow me to reuse the validation class without use of the field objects, and it would also allow better unit testing... However, it seems like and unnecessary layer of abstraction and also somewhat repetitive... Keep in mind, this is the most simple of all the validation. 如果要这样做,它将允许我在不使用字段对象的情况下重用验证类,并且还可以进行更好的单元测试...但是,这似乎是不必要的抽象层,并且在某种程度上是重复的。请记住,这是所有验证中最简单的。

Suggestions? 建议?

Why not have make Field objects responsible for their own validation? 为什么不让Field对象负责自己的验证?

class Field
{
    public bool Required { get; }
    public string Value { get; set; }

    // assuming that this method is virtual here
    // if different Fields have different validation logic
    // they should probably be separate classes anyhow and
    // simply implement a common interface of inherit from a common base class.
    public override bool IsValid
    {
        get { return Required && Value != String.Empty; }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM