C# 知识特性 Attribute
C#知识--获取特性 Attribute
特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集、类型、方法、属性等)相关联。特性与程序实体关联后,可在运行时使用“反射”查询特性,获取特性集合方法是GetCustomAttributes();
根据约定,所有特性名称都以单词“Attribute”结束,以便将它们与“.NET Framework”中的其他项区分。但是,在代码中使用特性时,不需要指定 attribute 后缀。在声明特性类时要以“Attribute”结束,使用时省略“Attribute”单词。
下面是几种使用特性的方法,菜鸟只是多看了一下总结一下,大神可以绕过:
类、程序集上的特性采用方法:
/// <summary>
/// 获取特性值方法
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static string OutputDescription(Type t)
{
var attributes = t.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
var attr = attribute as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
return t.ToString();
}
方法、属性采用扩展方法:
/// <summary>
/// 第一种获取特性值,适用只有单个特性
/// </summary>
public static class FingerGuessingGameTypeExtension
{
public static string GetEnumDescription(this FingerGuessingGameType enumType)
{
Type type = enumType.GetType();
MemberInfo[] memberInfo = type.GetMember(enumType.ToString());
if (memberInfo != null && memberInfo.Length > )
{
object[] attrs = memberInfo[].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > )
{
return ((DescriptionAttribute)attrs[]).Description;
}
} return enumType.ToString();
} public static string GetEnumValue(this FingerGuessingGameType enumType)
{
Type type = enumType.GetType();
MemberInfo[] memberInfo = type.GetMember(enumType.ToString());
if (memberInfo != null && memberInfo.Length > )
{
object[] attrs = memberInfo[].GetCustomAttributes(typeof(NameAttribute), false);
if (attrs != null && attrs.Length > )
{
return ((NameAttribute)attrs[]).Name;
}
} return enumType.ToString();
}
}
/// <summary>
/// 第二种获取特性值,适用有多个特性
/// </summary>
public static class FingerExtension
{
private static Dictionary<Enum, ValueDescriptionPair> m_Dic=null; public static string GetDescription(this FingerGuessingGameType enumType)
{
if (m_Dic == null)
{
Type type = enumType.GetType();
var allValues = Enum.GetValues(type).OfType<Enum>();
m_Dic = allValues.ToDictionary(p => p, p => GetDescriptionValue(type, p));
} ValueDescriptionPair valueDescription;
if (m_Dic.TryGetValue(enumType, out valueDescription))
{
return valueDescription.Description;
}
return enumType.ToString();
} public static string GetValue(this FingerGuessingGameType enumType)
{
if (m_Dic == null)
{
Type type = enumType.GetType();
var allValues = Enum.GetValues(type).OfType<Enum>();
m_Dic = allValues.ToDictionary(p => p, p => GetDescriptionValue(type, p));
} ValueDescriptionPair valueDescription;
if (m_Dic.TryGetValue(enumType, out valueDescription))
{
return valueDescription.Name;
}
return enumType.ToString();
} private static ValueDescriptionPair GetDescriptionValue(Type type, Enum value)
{
var valueDescriptionPair=new ValueDescriptionPair();
var enumName=Enum.GetName(type,value);
var description=type.GetField(enumName)
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.OfType<DescriptionAttribute>().FirstOrDefault();
var enumValue = type.GetField(enumName)
.GetCustomAttributes(typeof(NameAttribute), false)
.OfType<NameAttribute>().FirstOrDefault(); if (description != null)
{
valueDescriptionPair.Description = description.Description;
}
if (enumValue != null)
{
valueDescriptionPair.Name = enumValue.Name;
}
return valueDescriptionPair;
}
} public class NameAttribute:Attribute
{
public NameAttribute(string name)
{
Name = name;
}
public string Name { get; set; }
} public class ValueDescriptionPair
{
//Description 特性
public string Description { get; set; }
//Value 特性
public string Name { get; set; }
}
序列化XML(XMLSerialize):
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization; public static class XMLSerializeExtension
{
public static string Serialize<T>(this T value)
{
var result = string.Empty;
if (value == null)
{
return result;
}
try
{
var serializer = new XmlSerializer(typeof(T));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
serializer.Serialize(writer, value);
result = stringWriter.ToString();
}
}
catch (Exception ex)
{
throw new Exception("An error occurred while XML serialize", ex);
}
return result;
} public static T Deserialize<T>(this string value)
{
T retObj = default(T);
if (string.IsNullOrWhiteSpace(value) == true)
{
return retObj;
}
try
{
using (var rdr = new StringReader(value))
{
var serializer = new XmlSerializer(typeof(T));
retObj = (T)serializer.Deserialize(rdr);
}
}
catch (Exception ex)
{
throw new Exception("An error occurred while XML Deserialize", ex);
}
return retObj;
}
}
反射调用方法(Reflection)
Assembly assembly = Assembly.Load("ConsoleFileDemo");
Type classType = assembly.GetType("ConsoleFileDemo.XmlOperator");
ICase obj = Activator.CreateInstance(classType) as ICase;
//获取默认方法并调用方法
MethodInfo showMethod = classType.GetMethod("Show");
showMethod.Invoke(assembly, new object[]{"parameter"});
//获取无参方法并调用无参方法
MethodInfo show1 = classType.GetMethod("Show1",new Type[]{});
show1.Invoke(assembly,null);
//获取指定参数的方法并调用 int,string
MethodInfo show2 = classType.GetMethod("Show2", new Type[] {typeof (int)});
show2.Invoke(assembly, new object[] {}); MethodInfo show3 = classType.GetMethod("Show3", new Type[] { typeof(string) });
show3.Invoke(assembly, new object[] {"name"});
//获取指定私有方法并调用 string
MethodInfo show4 = classType.GetMethod("Show4",
BindingFlags.Instance |BindingFlags.Public | BindingFlags.NonPublic,
null,new Type[]{typeof(string)}, null);
show4.Invoke(assembly,new object[]{"name"}); //创建单例模式,反射使用私有构造函数实例化单例
Type typeSingle = assembly.GetType("ConsoleFileDemo.Singleton");
object objectSingle = Activator.CreateInstance(typeSingle, true);
C# 知识特性 Attribute的更多相关文章
- C# 知识特性 Attribute,XMLSerialize,
C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用“反射”查询特性,获取特性集合方 ...
- [C#] C# 知识回顾 - 特性 Attribute
C# 知识回顾 - 特性 Attribute [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5911289.html 目录 特性简介 使用特性 特性 ...
- .NET知识梳理——4.特性Attribute
1. 特性 1.1 特性Attribute 特性就是一个类,继承自Attribute抽象类(该类无抽象方法.避免实例化),约定俗成用Attribute类结尾,标记时可省略掉Attribu ...
- [C#] 剖析 AssemblyInfo.cs - 了解常用的特性 Attribute
剖析 AssemblyInfo.cs - 了解常用的特性 Attribute [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5944391.html 序 ...
- C# 自定义特性Attribute
一.特性Attribute和注释有什么区别 特性Attribute A:就是一个类,直接继承/间接继承Attribute B:特性可以在后期反射中处理,特性本身是没有什么*用的 C:特性会影响编译和运 ...
- 区分元素特性attribute和对象属性property
× 目录 [1]定义 [2]共有 [3]例外[4]特殊[5]自定义[6]混淆[7]总结 前面的话 其实attribute和property两个单词,翻译出来都是属性,但是<javascript高 ...
- .Net内置特性Attribute介绍
特性Attribute概述 特性(Attribute)是一种特殊的类型,可以加载到程序集或者程序集的类型上,这些类型包括模块.类.接口.结构.构造函数.方法.字段等,加载了特性的类型称之为特性的目标. ...
- 【点滴积累】通过特性(Attribute)为枚举添加更多的信息
转:http://www.cnblogs.com/IPrograming/archive/2013/05/26/Enum_DescriptionAttribute.html [点滴积累]通过特性(At ...
- 理解特性attribute 和 属性property的区别 及相关DOM操作总结
查一下英语单词解释,两个都可以表示属性.但attribute倾向于解释为特质,而property倾向于解释私有的.这个property的私有解释可以更方便我们下面的理解. 第一部分:区别点 第一点: ...
随机推荐
- 企业IT管理员IE11升级指南【17】—— F12 开发者工具
企业IT管理员IE11升级指南 系列: [1]—— Internet Explorer 11增强保护模式 (EPM) 介绍 [2]—— Internet Explorer 11 对Adobe Flas ...
- MySQL基础知识
一.MySQL安装 MySQL的下载 http://dev.mysql.com/downloads/mysql/ MySQL版本选择 MySQL功能自定义选择安装 1.功能自定义选择 2.路径自定义选 ...
- 使用自定义 classloader 的正确姿势
详细的原理就不多说了,网上一大把, 但是, 看了很多很多, 即使看了jdk 源码, 说了罗里吧嗦, 还是不很明白: 到底如何正确自定义ClassLoader, 需要注意什么 ExtClassLoade ...
- 如何开发一款堪比APP的微信小程序(腾讯内部团队分享)
一夜之间,微信小程序刷爆了行业网站和朋友圈,小程序真的能如张小龙所说让用户"即用即走"吗? 其功能能和动辄几十兆安装文件的APP相比吗? 开发小程序,是不是意味着移动应用开发的一次 ...
- 常用js功能函数集合
1.获取随机时间戳 function uniqueId(){ var a=Math.random,b=parseInt; return Number(new Date( ...
- 【转】c#、wpf 字符串,color,brush之间的转换
转自:http://www.cnblogs.com/wj-love/archive/2012/09/14/2685281.html 1,将#3C3C3C 赋给background this.selec ...
- ASP.NET Core真实管道详解[2]:Server是如何完成针对请求的监听、接收与响应的【上】
Server是ASP .NET Core管道的第一个节点,负责完整请求的监听和接收,最终对请求的响应同样也由它完成.Server是我们对所有实现了IServer接口的所有类型以及对应对象的统称,如下面 ...
- putty无密码登陆
1.打开puttygen.exe,点击Generate,然后按照说明用鼠标在空白处移动,生成密钥对. 2.保存私钥,不填passphrase.同时保存公钥,并打开公钥文件,将回车符去掉. 3.将公 ...
- 探寻<a>中的href和onclick
一.知识点: onclick的方法参数必须加引号 href跳转参数有长度限制 href中执行js会把encodeURIComponent()编码之后的东西自动解码,有时会影响参数传递 a标签中的onc ...
- 基于HTML5 Canvas 实现矢量工控风机叶轮旋转
之前在拓扑上的应用都是些静态的图元,今天我们将在拓扑上设计一个会动的图元--叶轮旋转. 先看看最后我们实现的效果:http://www.hightopo.com/demo/fan/index.html ...