一般來說,在.net中可以使用Type.GetCustomAttributes獲取類上的自定義屬性,可以使用PropertyInfo.GetCustomAttributes獲取屬性信息上的自定義屬性。
下面以定義一個簡單數據庫表的映射實體類來說明相關的使用方法,基于自定義類屬性和自定義類中的屬性的自定義屬性,可以方便的進行類標記和類中屬性的標記
創建一個類的自定義屬性,用于標識數據庫中的表名稱,需要繼承自Attribute類:
代碼如下:[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class TableAttribute : Attribute
{
private readonly string _TableName = "";
public TableAttribute(string tableName)
{
this._TableName = tableName;
}
public string TableName
{
get { return this._TableName; }
}
}
創建一個屬性的自定義屬性,用于標識數據庫表中字段的名稱,需要繼承自Attribute類:
代碼如下:[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class FieldAttribute : Attribute
{
private readonly string _FieldName = ""; ///數據庫的字段名稱
private System.Data.DbType _Type = System.Data.DbType.String; ///數據庫的字段類型
public FieldAttribute(string fieldName)
{
this._FieldName=fieldName;
}
public FieldAttribute(string fieldName,System.Data.DbType type)
{
this._FieldName=fieldName;
this._Type=type;
}
public string FieldName
{
get { return this._FieldName; }
}
public System.Data.DbType Type
{
新聞熱點
疑難解答
圖片精選