C# 对类属性启用/禁用验证

C# 对类属性启用/禁用验证,c#,.net,oop,C#,.net,Oop,很抱歉,我不知道我应该用什么来处理这个问题 问题是我在C#应用程序中使用属性和反射进行验证实现,类似这样 public class foo : validationBase { [RequiredAttribute("id is required")] public int id { get; set; } [RequiredAttribute("name is required")] public string name { get; set; } v

很抱歉,我不知道我应该用什么来处理这个问题

问题是我在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
属性所需的验证,请注意,单个属性可能会有更多的验证属性,并且可能需要一个属性的验证不启动,而另一个属性的验证应启动


请提供解决此问题的视图。

使用可标记的枚举,并将其传递并签入
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)
        {
            //...
        }
然后像这样验证道具:

    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,我不想这样做。