(.net core 3.1)详解C#特性(三)–特性获取扩展内容
案列:获取枚举上的描述
public enum DBType
{
[Name("oracle数据库")]
oracle=1,
[Name("mysqle数据库")]
mysql =2,
[Name("sqlserver数据库")]
sqlserver =3,
}
第二部:建立name特性类
[AttributeUsage(AttributeTargets.All,AllowMultiple =true,Inherited =true)]
public class NameAttribute : Attribute
{
public string name;
public NameAttribute(string name)
{
this.name = name;
}
}
第三部:调用方法来获取枚举上的描述
public static string GetRemark(DBType db) //扩展方法
{
Type type = db.GetType();
FieldInfo? fileInfo = type.GetField(db.ToString());
if (fileInfo != null)
{
if (fileInfo.IsDefined(typeof(NameAttribute), true))
{
NameAttribute remarkAttribute = (NameAttribute)fileInfo.GetCustomAttribute(typeof(NameAttribute), true);
return remarkAttribute.name;
}
}
return db.ToString();
}
最终调用:
var sql = DBType.mysql;
object str= DBExtend.GetRemark(sql);