//TestParamAttribute 是数据约束特性
//DBType、DBLenght 是具体的约束
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class TestParamAttribute : Attribute
{
private string dBType;
public string DBType
{
get { return dBType; }
set { dBType = value; }
}
private int dBLenght;
public int DBLenght
{
get { return dBLenght; }
set { dBLenght = value; }
}
}
//为类中的属性定义约束特性
class Tester
{
private int iD;
[TestParam(DBType="varchar",DBLenght=4)]
public int ID
{
get { return iD; }
set { iD = value; }
}
private string testName;
[TestParam(DBType="varchar",DBLenght=50)]
public string TestName
{
get { return testName; }
set { testName = value; }
}
}
Tester test = new Tester();
test.ID = 1;
test.TestName = "未完待续";
//读取对象的 属性、属性的特性、特性的具体约束
Type t = test.GetType();
PropertyInfo[] ps = t.GetProperties(); //类的属性列表,对应sql语句的参数(没有指明具体的对象)
foreach (PropertyInfo p in ps) //遍历属性列表,可以得到每一个属性
{
// label1.Text += "@" + p.Name + "=" + p.GetValue(test, null).ToString() + ",";//获取指明的对象‘test’的各个属性和值
//p.GetCustomAttributes(false) 获得每个属性的特性(Attribute)列表
//遍历特性列表,可以得到每个特性对象
foreach (object o in p.GetCustomAttributes(false))
{
if (o.GetType().Equals(typeof(TestParamAttribute))) //校验特性是否符合预设特性类型
{
TestParamAttribute tpa = (TestParamAttribute)o; //将对象强制转化为特性类型
//获取指明的对象‘test’的各个属性的特性中各个具体约束的值
label1.Text += "@" + p.Name + "(" + tpa.DBType + "," + tpa.DBLenght + ")" + "=" + p.GetValue(test,null).ToString() + ",";//p.GetValue(test, null) 函数指定需要获取的对象
}
}
}