【问题标题】:validation enable/disable on class properties验证启用/禁用类属性
【发布时间】:2013-09-09 09:03:58
【问题描述】:

对不起标题,不知道我应该用什么来解决这个问题。

问题是我在我的 C# 应用程序中使用属性和反射进行验证实现,就像这样。

public class foo : validationBase
{
    [RequiredAttribute("id is required")]
    public int id { get; set; }
    [RequiredAttribute("name is required")]
    public string name { get; set; }

    void save()
    {
       this.IsValid();
       //some code
    }
    void update()
    {
       this.IsValid();
       //some code
    }
    void delete()
    {
       // Need some magic here to ignore name attribute's required validation as only id 
       // is needed for delete operation
       this.IsValid();

       //some code
    }
}

正如您在删除操作中看到的那样,我不想验证 name 属性的必需验证,注意,单个属性可能有更多验证属性,并且可能要求一个属性的验证应该不开火,但其他人应该开火

请提供您的意见来解决这个问题。

【问题讨论】:

    标签: c# .net oop


    【解决方案1】:

    使用一个可标记的枚举,并通过它并在IsValid() 中检查它。如果操作需要验证,则验证它。是这样的:

        public sealed class RequiredAttributeAttribute : Attribute
        {
            private Operation _Operations = Operation.Insert | Operation.Update;
            public Operation Operations
            {
                get { return this._Operations; }
                set { this._Operations = value; }
            }
    
            public string ErrorMessage { get; set; }
        }
    
        [Flags]
        public enum Operation
        {
            Insert = 2,
            Update = 4,
            Delete = 6
        }
    

    然后像这样验证道具:

            void delete()
            {
                this.IsValid(Operation.Delete);
            }
    
    
            public bool IsValid(Operation operation)
            {
                //...
            }
    

    【讨论】:

    • insert、update、delete 是常用方法,但在大型应用程序类中可能/将会有很多方法,所以我认为我们不能这样定义操作枚举。还有一件事要记住的是 IsValid 是一种全局方法,它只是选择属性检查要检查的验证类型并验证它,仅此而已,此方法不应该知道更多,否则此方法将不会一个全球性的,我将不得不为每个我不想这样做的类编写一个不同的 IsValid。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多