验证属性不适用于List< T> [英] Validation Attribute doesn't work with List<T>

查看:54
本文介绍了验证属性不适用于List< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想继承来自List< T>并为此新类创建自定义验证属性。但它永远不会进入属性中的验证。

[AttributeUsage(AttributeTargets.Class,AllowMultiple = false)]
$
public class MyAttribute: ValidationAttribute {...}





[MyAttribute]

公共类MyList< T>:List< T> {...}

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class MyAttribute: ValidationAttribute{...}


[MyAttribute]
public class MyList<T>:List<T>{...}

有人可以提供帮助吗?

谢谢




推荐答案

这取决于您如何进行验证。如果正在验证的对象被声明为 类型List< T>而不是MyList< T>,只有List< T>中的属性。即使对象包含MyList< T>也将使用运行时
。这些属性不会像类中的方法那样通过继承以多态方式传播。

That depends on how you are doing the validation. If the object that is being validated is declared as being of type List<T> and not MyList<T>, only the attributes in List<T> will be used even if the object contains a MyList<T> at run time. The attributes are not propagated in a polymorphic way through inheritance like the methods in the class.

编辑:好吧,如果你自己进行验证,你可以读取继承类的属性。您只需要反映theObject.GetType()而不是typeof(theClass)。但如果您无法修改验证码,则无法执行此操作。

Well, if you do the validation yourself, you could read the attributes on the inherited class. You would just reflect on theObject.GetType() instead of typeof(theClass). But you can't do this if you can't modify the validation code.


这篇关于验证属性不适用于List&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆