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,XMLSerialize,的更多相关文章

  1. C# 知识特性 Attribute

    C#知识--获取特性 Attribute 特性提供功能强大的方法,用以将元数据或声明信息与代码(程序集.类型.方法.属性等)相关联.特性与程序实体关联后,可在运行时使用"反射"查询 ...

  2. [C#] C# 知识回顾 - 特性 Attribute

    C# 知识回顾 - 特性 Attribute [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5911289.html 目录 特性简介 使用特性 特性 ...

  3. .NET知识梳理——4.特性Attribute

    1. 特性 1.1        特性Attribute 特性就是一个类,继承自Attribute抽象类(该类无抽象方法.避免实例化),约定俗成用Attribute类结尾,标记时可省略掉Attribu ...

  4. [C#] 剖析 AssemblyInfo.cs - 了解常用的特性 Attribute

    剖析 AssemblyInfo.cs - 了解常用的特性 Attribute [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5944391.html 序 ...

  5. C# 自定义特性Attribute

    一.特性Attribute和注释有什么区别 特性Attribute A:就是一个类,直接继承/间接继承Attribute B:特性可以在后期反射中处理,特性本身是没有什么*用的 C:特性会影响编译和运 ...

  6. 区分元素特性attribute和对象属性property

    × 目录 [1]定义 [2]共有 [3]例外[4]特殊[5]自定义[6]混淆[7]总结 前面的话 其实attribute和property两个单词,翻译出来都是属性,但是<javascript高 ...

  7. .Net内置特性Attribute介绍

    特性Attribute概述 特性(Attribute)是一种特殊的类型,可以加载到程序集或者程序集的类型上,这些类型包括模块.类.接口.结构.构造函数.方法.字段等,加载了特性的类型称之为特性的目标. ...

  8. 【点滴积累】通过特性(Attribute)为枚举添加更多的信息

    转:http://www.cnblogs.com/IPrograming/archive/2013/05/26/Enum_DescriptionAttribute.html [点滴积累]通过特性(At ...

  9. 理解特性attribute 和 属性property的区别 及相关DOM操作总结

    查一下英语单词解释,两个都可以表示属性.但attribute倾向于解释为特质,而property倾向于解释私有的.这个property的私有解释可以更方便我们下面的理解. 第一部分:区别点 第一点:  ...

随机推荐

  1. keycloak docker-compose 运行

    内容很简单,主要是搭建一个可运行的keycloak 环境,方便开发测试,同时支持数据库的持久化 docker-compose 文件 version: "3" services: a ...

  2. supervisord 知识点

    官方英文: Supervisor: A Process Control System Supervisor: 一个进程管理系统. Supervisor is a client/server syste ...

  3. webpack 中,loader、plugin 的区别

    loader 和 plugin 的主要区别: loader 用于加载某些资源文件. 因为 webpack 只能理解 JavaScript 和 JSON 文件,对于其他资源例如 css,图片,或者其他的 ...

  4. 使用 RSA 非对称加密保证数据不被篡改 java 例子代码

    原理: 对原始数据 生成有序的json 字符串,然后取 摘要,然后 对摘要 进项 分对称加密.( 不对原数据加密是应为 原数据太大,加解密速度太慢,非对称加密都不 挺慢的.在摘要函数具有雪崩效应 ,原 ...

  5. hadoop mapreduce 简单例子

    本例子统计 用空格分开的单词出现数量(  这个Main.mian 启动方式是hadoop 2.0 的写法.1.0 不一样 ) 目录结构: 使用的 maven : 下面是maven 依赖. <de ...

  6. PHP 对象转数组 Object转array

    //调用这个函数,将其幻化为数组,然后取出对应值 public static function object_array($array) { if(is_object($array)) { $arra ...

  7. slice.indices()/collections.Counter笔记

    关于slice.indices() >>> help(slice) Help on class slice in module builtins: class slice(objec ...

  8. 关于Firedac的一点看法

    Firedac集成在Delphi中已经有几个版本了,偶尔也拖到Form上试着用用,虽然知道Firedac有可能是最终的(或很很长时间内)数据访问技术,可一直不能接受它,其中最大的原因就是过于“复杂” ...

  9. FPGA中关于SPI的使用

    FPGA中关于SPI的使用 信息来源 SPI Flash的编程 最新的SPI不止有4根信号线,可以增加到支持4bit的数据宽度 SPI Flash Basics 能够扩展成4bit数据的是MOSI信号

  10. delphi中Time消息的使用方法

    unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...