C# 自定义对象验证设计 [英] C# Custom Object Validation Design

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

问题描述

我目前必须验证我的应用程序的自定义字段对象.简单地说,每个 Field 对象都包含有关字段验证的信息以及字段的值.我正在批量验证字段,所以目前,我有一个验证类,每个验证都有一个方法.对于必填字段,它看起来像这样:

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. 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.

建议?

推荐答案

为什么不用让 Field 对象负责自己的验证?

Why not have make Field objects responsible for their own validation?

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; }
    }
}

这篇关于C# 自定义对象验证设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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