1

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

问题是我在我的 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属性的必需验证,注意单个属性可能有更多验证属性,并且可能要求一个属性的验证不应该触发,而其他的应该

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

4

1 回答 1

0

Use a flag-able enum and, pass it and check it in IsValid(). If an opeation requires to be validaed, then verify it. Somthing like this:

    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
    }

then validate the props like this:

        void delete()
        {
            this.IsValid(Operation.Delete);
        }


        public bool IsValid(Operation operation)
        {
            //...
        }
于 2013-09-09T09:22:40.897 回答