class Program
{
static void Main(string[] args)
{
var userInfo = new UserInfo();
var type = userInfo.GetType();
// 讀取類級別 TableAttribute
var tableAttr = (TableAttribute)type.GetCustomAttributes(false)[0];
Console.WriteLine($"數據表名:{tableAttr.TableName}");
// 遍歷屬性讀取 ColumnAttribute
foreach (var prop in type.GetProperties())
{
foreach (var attr in prop.GetCustomAttributes(false))
{
if (attr is ColumnAttribute colAttr)
{
string colName = colAttr.ColumnName ?? prop.Name;
Console.WriteLine($"字段名:{colName}");
Console.WriteLine($"字段類型:{colAttr.DbType}");
}
}
}
}
}

輸出對應數據庫表名、字段名、字段類型,實現元數據驅動**的OR映射基礎。
Type.GetCustomAttributes(inherit):獲取類/結構/接口級特性。PropertyInfo.GetCustomAttributes(inherit):獲取屬性級特性。AttributeUsage控制特性作用目標(AttributeTargets.Property等)、是否可多次、是否繼承。AttributeReader工具類,統一異常處理與緩存。inherit=true處理繼承鏈特性。DisplayName/Description等標準特性豐富元數據。