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);
}
}