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. 数据格式转换(一)PDF转换技术

         PDF(Portable Document Format)文件格式是Adobe公司开发的电子文件格式. 这样的文件格式与操作系统平台无关.这一特点使它成为在Internet上进行电子文档发行 ...

  2. Unity5 图形系统介绍 学习

  3. webpack基本配置文件

    entry(入口文件) 可以传字符串,数组,对象三种格式(字符串和数组默认生成main.js,均生成一个文件,对象有几个入口文件,生成几个文件).默认值为./src/index.js.entry可以传 ...

  4. java考试感受

    开学不久,我们进行了一次java程序考试.在此之前,老师要求我们在假期自学java并提前发了一个考试样卷,要求用数组编写一个学生信息管理系统并能够实现一系列的功能.由于我早早的便完成了这道题.因此对这 ...

  5. Spring技术内幕总结 - AOP概述

    AOP是Aspect-Oriented Programming(面向方面/切面编程)的简称.Aspect是一种新的模块化机制,用来描述分散在对象.类或函数中的横切关注点.分离关注点使解决特定领域问题的 ...

  6. JS 从HTML页面获取自定义属性值

    <select id="nextType" data-parameter="@Model.NextType"> <option value=& ...

  7. alias 创建别名

    在我们的"/home/用户名/"的目录下,会有一个“.bashrc”文件,修改步骤如下: 在文件的末尾添加: alias 想要的别名=文件路径(文件路劲加引号)例如:alias p ...

  8. CENTOS 7 64BIT,MYSQL5.7安装与配置

    配置MYSQL YUM源 wget -P ./ http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm ######## ...

  9. ML: 聚类算法R包-层次聚类

    层次聚类 stats::hclust stats::dist    R使用dist()函数来计算距离,Usage: dist(x, method = "euclidean", di ...

  10. how to install an older version of package via NuGet?

    转载 http://stackoverflow.com/questions/10206090/how-to-install-an-older-version-of-package-via-nuget ...