C#編程經常使用特性,相當於類的元數據
自定義特性繼承System.Attribute類
自定特性命名後綴為Attribute,這樣符合微軟的命名風格,也符合編譯器的搜索規則
使用[]語法使用自定義特性
可以使用反射來查看自定義特性
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class CTest2Attribute : Attribute
{
private string _strTableName = string.Empty;
public string TableName
{
get { return (_strTableName); }
set { _strTableName = value; }
}
private string _fieldName = string.Empty;
public string FieldName
{
get { return (_fieldName); }
set { _fieldName = value; }
}
}
[CTest2(TableName = "測試表格1", FieldName = "字段1")]
public class TestAtt2
{
public string Temp { get; set; }
}
object[] attrs = typeof(TestAtt2).GetCustomAttributes(true);
foreach (object obj in attrs)
{
CTest2Attribute att = obj as CTest2Attribute;
if (att != null)
{
Console.WriteLine(att.TableName);
}
}