net获取静态类与非静态类自定义属性
作者:互联网
/// <summary>
/// 调用第三方服务出错 一级宏观错误码
/// </summary>
[Description("调用第三方服务出错")]
public const string C0001 = "C0001";
/// <summary>
/// 中间件服务出错 二级宏观错误码
/// </summary>
[Description("中间件服务出错")]
public const string C0100 = "C0100";
/// <summary>
/// 根据code获取描述
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public static string? GetDescription(string code)
{
//静态类读取
// var fields = typeof(ApiResultCode).GetFields();//读取的Fields是不包含{get;}访问器的
var field = typeof(ApiResultCode).GetField(code);
if (field == null) {
return null;
}
var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes == null) {
return null;
}
dynamic displayAttribute = attributes[0];
return displayAttribute?.Description; //动态属性
////获取非静态的
//var type = typeof(ApiResultCode).GetProperty(code);
//if (type == null) return null;
//var attributes = type.GetCustomAttributes(typeof(DescriptionAttribute), false);
//if (attributes == null) return null;
//dynamic displayAttribute = attributes[0];
//return displayAttribute?.Description; //动态属性
}
标签:code,return,自定义,静态,typeof,var,attributes,net,null 来源: https://www.cnblogs.com/nfmc/p/16399820.html