首页 > c#-4.0 > 使用自定义属性验证C#类字段

使用自定义属性验证C#类字段 (Validating C# class fields using custom Attributes)

2010-08-23 c#-4.0

问题

class Employee
{
  [ValueNotEmpty("Empty strings not allowed"]
  public string Name{get;set;}
}

"ValueNotEmpty" 我是一个自定义属性。我尝试使用YABOV库,但我必须显式调用基类的Validate方法来验证自定义属性并返回验证消息。

在实现类中,我使用反射来设置字段上的值。"Name"当我在"Name"字段上设置值时,我希望try块抛出一个异常说明"Empty strings not allowed"。我有什么办法可以做到这一点,而无需显式调用方法来验证类,当我为该字段设定值?

解决方法

对这个问题的一些想法:

如果您的属性调用PropertyChanged事件,则可能有一种机制使用它来验证它。例如,与数据绑定相结合。如果您没有PropertyChanged,则需要显式调用Validate,除非您使用的是AOP。

在设置值时执行代码需要AOP。在.Net标准库中,没有包含AOP技术,您必须集成一个(例如Spring)。AOP需要代码生成或字节码增强。所以这不是一件小事。

问题

class Employee
{
  [ValueNotEmpty("Empty strings not allowed"]
  public string Name{get;set;}
}

"ValueNotEmpty" is a custom attribute.I tried using YABOV library but i have to call Validate method of the base class explicitly to validate the custom attributes and return the validation messages.

In the implementation class, i use reflection to set values on "Name" field.When i set value on "Name" field i expect the try block to throw an exception saying "Empty strings not allowed".Is there any way i can do this without explicitly calling a method to validate the class when i set value for the field?.

解决方法

A few thoughts to this problem:

If your property calls a PropertyChanged event, there might be a mechanism which uses this to validate it. For instance in combination with data binding. If you don't have PropertyChanged, you need to call Validate somewhere explicitly, unless you're using AOP.

Executing code when you just set a value would require AOP. In .Net standard libraries, there is no AOP technology included, you would have to integrate one (eg. Spring). AOP requires code generation or byte-code enhancement. So it's not a trivial thing.

相似信息