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. NET使用NPOI组件导出Excel-入门示例及通用方法

    一.Excel导入及导出问题产生:   从接触.net到现在一直在维护一个DataTable导出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题:   导出问题:   如果是as ...

  2. 深入浅出:MySQL的左连接、右连接、内连接

    http://blog.csdn.net/wyzxg/article/details/7276979 三种连接的语法 为便于更多的技友快速读懂.理解,我们只讨论2张表对象进行连接操作的情况,大于2张表 ...

  3. pstStream->pstPack[i].pu8Addr详解

    /****************************************************************************** * funciton : save H2 ...

  4. URL整理

    Airtest project官网 http://airtest.netease.com/ poco辅助文档:http://poco.readthedocs.io/zh_CN/latest/index ...

  5. day 27 网络通信协议 tup udp 下的socket

    1.osi七层模型 通信流程 socket(抽象层): 结合上图来看,socket在哪一层呢,我们继续看下图 socket在内的五层通讯流程: 2.TCP/UDP的区别: TCP是以数据流的形式传输, ...

  6. [转]C# FTP操作类

      转自 http://www.cnblogs.com/Liyuting/p/7084718.html using System; using System.Collections.Generic; ...

  7. 没有了CommonsChunkPlugin,咱拿什么来分包(译)

    webpack 4 移除 CommonsChunkPlugin,取而代之的是两个新的配置项(optimization.splitChunks 和 optimization.runtimeChunk). ...

  8. Apache 配置Https 转发Tomcat Http

    Apache 相对于nginx的配置对比起来相当复杂啦,朋友之前的系统使用的是Apache需要增加一个虚拟主机,主要配置从Apache转发Tomcat. 首先需要拆解下步骤: Apache 支持Htt ...

  9. Linux中chown和chmod的区别和用法

    转载自:http://www.cnblogs.com/EasonJim/p/6525242.html chmod修改第一列内容,chown修改第3.4列内容: chown用法: 用来更改某个目录或文件 ...

  10. Ribbon Ping机制

    在负载均衡器中,提供了 Ping 机制,每隔一段时间,会去 Ping 服务器,判断服务器是否存活,该工作由 com.netflix.loadbalancer.IPing 接口的实现类负责,如果单独使用 ...