C# 知识特性 Attribute,XMLSerialize,

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);
上一篇:bzoj4817/luogu3703 树点涂色 (LCT+dfs序+线段树)


下一篇:class的二般用法