.NET Attribute使用实例
2009-02-28 20:03 Iron 阅读(429) 评论(0) 编辑 收藏 举报这里介绍一下.NET的Attribute,在早些时候被翻译作属性,和property混淆了。现在一般都翻译为特性或特征,它可以给一个类或者类的成员附加一些额外的特征或者功能。在.NET里面的System.Arribute作为其基类,所有继承自他的,并且类名以Attribute结尾的类型都可以作为Attribute实用,这里有一个约束,定义的时侯类名要以Attribute结尾,但是使用的时候要去掉Attibute。.NET类库预定义了很多的特性来实现很多的功能,这里我们通过Attribute类来标示类成员的特性,并且通过反射来获取来标示类成员与数据库的映射。
首先我们通过一个例子来看看Attribute的特性
class TestAttribute:System.Attribute
{
public TestAttribute(string message)
{
throw new Exception("error:"+message);
}
}
class Tester
{
[Test("Can not run this method!")]
public void Cannotrun()
{
}
public static Main(sting[] args)
{
Tester t=new Tester();
t.Cannotrun();
}
}
我们现在就是来构造一个Attribute的类来存储一个属性的类型,长度,映射字段等数据
namespace Alexander.Xbase.Interface
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class ParamAttribute:Attribute
{
private string _parameterType;
public string ParameterType
{
get
{ return _parameterType; }
set
{ _parameterType = value; }
}
private int _parameterLength;
public int ParameterLength
{
get
{ return _parameterLength; }
set
{ _parameterLength = value; }
}
private string _srccolumn;
public string Srccolumn
{
get
{ return _srccolumn; }
set
{ _srccolumn = value; }
}
public ParamAttribute(string ptype, int len)
{
_parameterType = ptype;
_parameterLength = len;
//throw new Exception("can not use");
}
public ParamAttribute(string ptype, int len,string src)
{
_parameterType = ptype;
_parameterLength = len;
_srccolumn = src;
//throw new Exception("can not use");
}
}
}
使用的时候
定义一个实体类:
class tb
{
private string _aaa;
[Param("NChar",10)]
public string aaa
{
get
{ return _aaa; }
set
{ _aaa = value; }
}
private string _bbb;
[Param("NChar", 10)]
public string bbb
{
get
{ return _bbb; }
set
{ _bbb = value; }
}
}
这样子就把映射的类型,长度都存储到特征里面。
感谢:http://www.cnblogs.com/Alexander-Lee/archive/2007/01/24/hbh-orm-06.html