首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

反射學習系列 2-特性 (二) 定義表與欄位對應特性

     編輯:關於C語言

特性基本概念

特性本質是類別,可有多個建構函數。套用特性時可指定建構函數參數,或用「屬性名=值」語法設定屬性。所有特性繼承自 System.Attribute。

實體類別:User

[Table("User")]
public class User
{
    [Colum("userID", DbType = DbType.Int32)]
    public int UserID { get; set; }
    [Colum("UserName", DbType = DbType.String)]
    public string UserName { get; set; }
}

TableAttribute 定義

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class TableAttribute : Attribute
{
    private string _tableName;
    public TableAttribute() { }
    public TableAttribute(string tableName) { _tableName = tableName; }
    public string TableName
    {
        get { return _tableName; }
        set { _tableName = value; }
    }
}
  • AttributeTargets.Class:僅能套用於類別。
  • AllowMultiple = false:同一類別不可重複套用。
  • Inherited = false:不繼承至衍生類別。

ColumAttribute 定義

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class ColumAttribute : Attribute
{
    private string _columName;
    private DbType _dbType;
    public ColumAttribute() { }
    public ColumAttribute(string columName) : this() { _columName = columName; }
    public ColumAttribute(string columName, DbType dbType) : this(columName) { _dbType = dbType; }
    public string ColumName { get { return _columName; } set { _columName = value; } }
    public DbType DbType { get { return _dbType; } set { _dbType = value; } }
}

套用於屬性,支援指定資料庫型別(DbType)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved