Attribute的定义示例 :
AttributeTargets.Class 枚举类型,标签级别定义,此枚举标识类级别
AllowMultiple 反复定义
Inherited 被子类继承
[AttributeUsage(AttributeTargets.Class,AllowMultiple=false,Inherited=false)]
public class TableAttribute : Attribute
{
private string tableName;
public string TableName
{
get { return tableName; }
set { tableName = value; }
}
public TableAttribute()
{
this.tableName = null;
}
public TableAttribute(string tableName)
{
this.tableName = tableName;
}
}
[AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=false)]
public class ColumnAttribute : Attribute
{
public ColumnAttribute()
{
this.columnName = null;
this.dbType = DbType.String;
}
public ColumnAttribute(string columnName)
{
this.columnName = columnName;
}
public ColumnAttribute(string columnName, DbType dbType)
: this(columnName)
{
this.dbType = dbType;
}
private string columnName;
public string ColumnName
{
get { return columnName; }
set { columnName = value; }
}
private DbType dbType;
public DbType DbType
{
get { return dbType; }
set { dbType = value; }
}
}
标签的使用:
[Table("UserInfo")]
public class UserInfo
{
private int userId;
[Column("UserId",DbType.Int32)]
public int UserId
{
get { return userId; }
set { userId = value; }
}
private string userName;
[Column(UserName,DbType.String)]
public string UserName
{
get { return userName; }
set { userName = value; }
}
}
反射方式:
UserInfo userInfo = new UserInfo();
Type type = userInfo.GetType();
TableAttribute ta = (TableAttribute)type.GetCustomAttributes(false)[0];
Console.WriteLine("数据表名:" + ta.TableName);
PropertyInfo[] infos = type.GetProperties();
//反射属性
foreach (PropertyInfo info in infos)
{
//反射属性标签的内容
object[] attributes = info.GetCustomAttributes(false);
foreach (object att in attributes)
{
if (att is ColumnAttribute)
{
ColumnAttribute ca = att as ColumnAttribute;
string cn = ca.ColumnName == null ? info.Name : ca.ColumnName;
Console.WriteLine("字段名:" + cn);
Console.WriteLine("字段类型:" + ca.DbType);
}
}