[英]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.为什么不以另一种方式解决这个问题。
Translations
class as it is without the attribute.保持Translations
类没有属性。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.