C# 自定义特性
来源:互联网 发布:淘宝官方买家秀入口 编辑:程序博客网 时间:2024/05/21 18:38
//自定义特性类
[System.AttributeUsage(System.AttributeTargets.Field |System.AttributeTargets.Enum)]
publicclass PropertiesDesc : System.Attribute
{
public string Desc { get; set; }
public PropertiesDesc(string desc)
{
Desc = desc;
}
}
public class PropertiesUtils
{
private static Dictionary<Type,Dictionary<string, string>> cache = new Dictionary<Type,Dictionary<string, string>>();
public static string GetDescByProperties(object p)
{
var type = p.GetType();
if (!cache.ContainsKey(type))
{
Cache(type);
}
var fieldNameToDesc = cache[type];
var fieldName = p.ToString();
returnfieldNameToDesc.ContainsKey(fieldName) ? fieldNameToDesc[fieldName] :string.Format("Can not found such desc for field `{0}` in type`{1}`", fieldName, type.Name);
}
private static void Cache(Type type)
{
var dict = new Dictionary<string,string>();
cache.Add(type, dict);
var fields = type.GetFields();
foreach (var field in fields)
{
var objs =field.GetCustomAttributes(typeof(PropertiesDesc), true);
if (objs.Length > 0)
{
dict.Add(field.Name, ((PropertiesDesc)objs[0]).Desc);
}
}
}
}
//枚举对象
public enumWeekday
{
[PropertiesDesc("星期一")]
Monday = 1,
[PropertiesDesc("星期二")]
Tuesday = 2,
[PropertiesDesc("星期三")]
Wednesday = 3,
[PropertiesDesc("星期四")]
Thursday = 4,
[PropertiesDesc("星期五")]
Friday = 5,
[PropertiesDesc("星期六")]
Saturday = 6,
[PropertiesDesc("星期日")]
Sunday = 6
}
调用:
var str =PropertiesUtils.GetDescByProperties(Weekday.Friday);
Console.Write(str);
- C#自定义特性
- C#自定义特性
- C#自定义特性介绍
- C#自定义特性
- C# 自定义特性
- C#自定义特性
- C#自定义特性
- C# 自定义特性
- c#自定义特性
- C# 自定义特性的使用
- C#自定义特性和反射
- C# 使用自定义的特性Attribute
- C#高级编程七十八天----自定义特性
- c# 特性/属性(Attribute) 以及使用反射查看自定义特性
- c# 特性/属性(Attribute) 以及使用反射查看自定义特性
- c#通过反射获取类上的自定义特性
- C# 反射通过GetCustomAttributes方法,获得自定义特性
- c#通过反射获取类上的自定义特性
- 使用JS对数组进行排序,设置计时器和计数器
- 解决启动报错:Failed to destroy end point associated with ProtocolHandler["ajp-nio-8009"]
- c++ 十进制、十六进制和BCD的相互转换
- OpenGL中的坐标系
- 关于 Xcode7网络请求的Http 协议改为 Https 协议的程序修改
- C# 自定义特性
- Spring在代码中获取bean的几种方式
- android studio 优秀插件
- 虚拟机ping不通主机
- iOS应用开发最佳实践:编写高质量的Objective-C代码
- Dynamics CRM2015 页面导航栏顶部全局快速查找功能配置
- 集合框架---TreeSet存储自定义对象
- Xcode真机测试could not find developer disk image解决方法
- 关于Spring的69个面试问答——终极列表