日期:2014-05-18  浏览次数:20448 次

{ 100分 } ,求一个特性(Attributes)在Asp.net项目中的实际例子。急,好了立即给分。
如题,请您帮我一把。

------解决方案--------------------
翻了半天,才在箱底找了,此文,希望对你有帮助。


.net Attribute效验的使用方法
近来在做.net的项目,因为会用到实体类,就想在实体类上用Attribute信息来对实体类中的属性进行配制。因为在网上没能找到类似的包,就只能在五一的时候自己写了一个,以下是这个包的使用方法。

首先:需要在web.config中配制验证器。

xml 代码

<configSections>
<sectionGroup name= "Validate ">
<section name= "Validators " type= "Validator.Configuration.ValidateConfigurationSection, Validator "/>
</sectionGroup>
</configSections>
<Validate>
<Validators>
<Validator name= "Email " validateType= "match " validateInfo= "\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* " message= "{0} is\ 't Email "/>
<Validator name= "NotNull " validateType= "inner " validateInfo= "NotNull " message= "{0}不能为空! "/>
<Validator name= "Length " validateType= "inner " validateInfo= "Length " message= "{0}字符串长度不能超过{1}! "/>
<Validator name= "Decimal " validateType= "inner " validateInfo= "Decimal " message= "{0}必须大于{1},{0}必须小于{1} "/>
<Validator name= "TestClass " validateType= "clazz " validateInfo= "Validator.Test.TestObj, Validator " message= "{0}class测试! "/>
</Validators>
</Validate>


Validator 的Name为验证器的名称,这里要以attribute类中工ValidatorName相对应,validateType是一个枚举,他有代表着,验 证器的三个类型,inner是使用内置的验证器,match是正则表达式的验证器,clazz是实现iValidator的类做的验证器。后面validateInfo在种自的类型中有各自的意义,在inner时,他要以Name相同;在match时,他是一个正则表达式;在clazz时,他是一个类的AssemblyInfo信息,要显示的错误信息。

第二部,为每一个验证器写一个Attribut.

c# 代码
public class NotNullValidateType : ValidateType
{
public NotNullValidateType(String sColName)
{
this.ColName = sColName;
this.ValidatorName = "NotNull ";
}
}

在这里我们必须继承ValidateType类,在这个类里我们实现了IValidateType的接口,我们必须为这个接口中的属性进行填值。
其中ValidatorName 是一个必输的,他就是在web.config 的配置的验证器名,ColName 是字段的名字,param 是要传入的参数。

c# 代码
public interface IValidateType
{
string Param{get;set;}

string ValidatorName{get;set;}

string ColName{get;set;}
}

第三部,验证器的编写

inner验证器是内置的验证器,所以我们不能添加他。

match验证器是正则表达式验证器,只要在配置中配制好就可以拥有这个功能。

clazz验证器是自定义类验证器,这个类配置到config中,且已经实现了IValidator.cs类。


c# 代码
public class TestObj :ValidateType, IValidator
{
public TestObj()
{
this.ValidatorName = "TestClass ";
}

public TestObj(String sColName)
{
this.ColName = sColName;
this.ValidatorName = "TestClass ";
}

#region IValidator 成员

public bool validator(object value, ValidatorInfo vi, IValidateType vt)
{
//Console.Write( "hello world gettype ");
return false;
}
#endregion
}


最后, attribute的使用,

c# 代码
public class UserObject
{
string _code;
string _email;
[ValidateType( "NotNull ")]
[TestObj]
[StringLengthValidateType(2)]
public string Code
{
get { return _code; }
set { _code = value; }
}
[EmailValidateType(null)]
public string Email
{
get { return _email; }
set { _email = value