简体   繁体   English

如何在其对象之一中忽略类的自定义属性

[英]How to ignore custom attribute of class in one of its object(s)

I have created custom attribute that is used on Translation class, which is applied as following:我创建了用于Translation类的自定义属性,其应用如下:

[ValidateTranslationDictionary]
public class Translations : Dictionary<string, string>{  }

The attribute code is:属性代码为:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public class ValidateTranslationDictionaryAttribute : ValidationAttribute
{
    public ValidateTranslationDictionaryAttribute() : base() { }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        DoSomeValidationHere(); //....
        return ValidationResult.Success; //for example
    }
}

My default scenario is to apply the validation attribute on all objects of the Translation class (currently work perfectly),我的默认场景是在Translation类的所有对象上应用验证属性(目前工作完美),

but in some cases I need to skip this validation on some object, example:但在某些情况下,我需要跳过对某个对象的验证,例如:

public class Test{
    public Translations WithValidation{ get; set; }
    public Translations WithoutValidation{ get; set; }
}

There is a way to not run the validation on WithoutValidation property of Test class but keep it on the others objects?没有办法不对Test类的WithoutValidation属性运行验证,而是将其保留在其他对象上?

Also I tried to add boolean to the attribute as flag to run the validation, and put the attribute on both class and property, but the attribute validator run 2 times, first from property, and the second call from the class我还尝试向属性添加布尔值作为运行验证的标志,并将属性放在类和属性上,但属性验证器运行 2 次,第一次来自属性,第二次来自类

hint : can I add another attribute called for example IgnoreValidationAttribute , and make it skip ValidateTranslationDictionary attribute?提示:我可以添加另一个名为IgnoreValidationAttribute属性,并使其跳过ValidateTranslationDictionary属性吗?

So the thing is that Translations object does not really require validation, at least not all of the time.所以问题是Translations对象并不真正需要验证,至少不是所有时间。

Why not approach this another way.为什么不以另一种方式解决这个问题。

  • Leave the Translations class as it is without the attribute.保持Translations类没有属性。
  • Then apply the attribute on attribute level然后在属性级别应用属性
public class Test{
    [ValidateTranslationDictionary]
    public Translations WithValidation{ get; set; }
    public Translations WithoutValidation{ get; set; }
}

And if you need the exact same class with validations, then如果你需要与验证完全相同的类,那么

[ValidateTranslationDictionary]
public class ValidTranslations: Translations 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM