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

反射學習系列 2-特性 (三) 欄位特性完整定義

     編輯:關於C語言

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 virtual string ColumName
    {
        get { return _columName; }
        set { _columName = value; }
    }

    public DbType DbType
    {
        get { return _dbType; }
        set { _dbType = value; }
    }
}

設計重點

  • 多建構函數鏈:ColumAttribute() → (string) → (string, DbType),避免程式碼重複。
  • ColumName 設為 virtual,允許衍生特性覆寫。
  • DbType 屬性對應 System.Data.DbType 列舉,支援精確型別映射。
  • AttributeUsage 限制只能套用於屬性(AttributeTargets.Property)。

此特性配合 TableAttribute,構成簡易 ORM 映射的特性基礎設施。

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