特性本質是類別,可有多個建構函數。套用特性時可指定建構函數參數,或用「屬性名=值」語法設定屬性。所有特性繼承自 System.Attribute。
[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; }
}
[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:不繼承至衍生類別。[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)。