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

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

问题描述

我目前必须为我的应用程序验证自定义字段对象。简而言之,每个Field对象都包含有关该字段的验证以及该字段的值的信息。
我正在批量验证字段,因此目前,我有一个验证类,该类具有用于每个验证的方法。对于必填字段,它看起来像这样:

  private void RequiredFields()
{
foreach( allFields中的字段字段)
{
if(((field.Required == true)&&(field.Value == string.Empty))
{
字段。 isValid = false;
}
}
}

现在我的问题是我感觉我应该对验证进行抽象化,所以不必说:

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

...我会添加一个验证类,接受值并将其转换为:

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

如果我这样做,它将允许我重用验证类不使用字段对象,也可以进行更好的单元测试...但是,这似乎是不必要的抽象层,并且在某种程度上是重复的...请记住,这是所有验证中最简单的。 / p>

建议?

解决方案

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

  class字段
{
public bool必需的{get; }
公用字串值{组; }

//假定此方法是虚拟的
//如果不同的字段具有不同的验证逻辑
//无论如何它们都应该是单独的类,而
/ /简单地实现从通用基类继承的通用接口。
公共优先布尔值IsValid
{
get {return Required&&值!= String.Empty; }
}
}


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.

Suggestions?

解决方案

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天全站免登陆