C#遍历类对象获取属性名、值、Description
声明对象
using System;
using System.ComponentModel;
using System.Reflection;
[Description("用户")]
public class User
{
[Description("编号")]
public int Id { get; set; }
[Description("姓名")]
public string Name { get; set; }
[Description("生日")]
public DateTime BirthDay { get; set; } = DateTime.Now;
}
遍历获取对象
var u = new User();
PropertyInfo[] propertiesInfos= u.GetType().GetProperties();
foreach (var pi in propertiesInfos)
{
var name = pi.Name;//获取属性名
var val = pi.GetValue(u);//获取属性值
var prType = pi.PropertyType;//获取属性类型
var type = string.Empty;
if (prType == typeof(string))
type = "字符串";
else if (prType == typeof(DateTime))
type = "日期";
else if (prType == typeof(int))
type = "整型";
var descAttr = Attribute.GetCustomAttribute(pi, typeof(DescriptionAttribute)) as DescriptionAttribute;
string desc=string.Empty;
if(descAttr!=null)
desc = descAttr.Description;// //获取属性Description attribute
if (val is null)
{
pi.SetValue(u, "test");//给属性赋值
val = pi.GetValue(u);
}
Console.WriteLine($"属性名:{name},属性值:{val},类型:{type},属性描述:{desc}");
}
声明自定义Attribute
public sealed class CustomAttribute : Attribute
{
private readonly string _custom;
public string Custom
{
get { return _custom; }
}
public CustomAttribute(string custome)
{
_custom = custome;
}
}
使用自定义Attribute
[Description("用户")]
[Custom("自定义用户")]
public class User
{
[Description("编号")]
[Custom("自定义ID")]
public int Id { get; set; }
[Description("姓名")]
public string Name { get; set; }
[Description("生日")]
public DateTime BirthDay { get; set; } = DateTime.Now;
}
创建静态扩展类
using System;
using System.Collections.Concurrent;
using System.Reflection;
public static class CustomAttributeExtensions
{
/// <summary>
/// Cache Data
/// </summary>
private static readonly ConcurrentDictionary<string, object> Cache = new ConcurrentDictionary<string, object>();
/// <summary>
/// 获取CustomAttribute Value
/// </summary>
/// <typeparam name="TAttribute">Attribute的子类型</typeparam>
/// <typeparam name="TReturn">TReturn的子类型</typeparam>
/// <param name="sourceType">头部标有CustomAttribute类的类型</param>
/// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
/// <returns>返回Attribute的值,没有则返回null</returns>
public static TReturn GetCustomAttributeValue<TAttribute, TReturn>(this Type sourceType, Func<TAttribute, TReturn> attributeValueAction)
where TAttribute : Attribute
{
return _getAttributeValue(sourceType, attributeValueAction, null);
}
/// <summary>
/// 获取CustomAttribute Value
/// </summary>
/// <typeparam name="TAttribute">Attribute的子类型</typeparam>
/// <typeparam name="TReturn">TReturn的子类型</typeparam>
/// <param name="sourceType">头部标有CustomAttribute类的类型</param>
/// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
/// <param name="propertyName">field name或property name</param>
/// <returns>返回Attribute的值,没有则返回null</returns>
public static TReturn GetCustomAttributeValue<TAttribute, TReturn>(this Type sourceType, Func<TAttribute, TReturn> attributeValueAction, string propertyName)
where TAttribute : Attribute
{
return _getAttributeValue(sourceType, attributeValueAction, propertyName);
}
#region private methods
private static TReturn _getAttributeValue<TAttribute, TReturn>(Type sourceType, Func<TAttribute, TReturn> attributeFunc, string propertyName)
where TAttribute : Attribute
{
var cacheKey = BuildKey<TAttribute>(sourceType, propertyName);
var value = Cache.GetOrAdd(cacheKey, k => GetValue(sourceType, attributeFunc, propertyName));
if (value is TReturn) return (TReturn)Cache[cacheKey];
return default(TReturn);
}
private static string BuildKey<TAttribute>(Type type, string propertyName) where TAttribute : Attribute
{
var attributeName = typeof(TAttribute).FullName;
if (string.IsNullOrEmpty(propertyName))
{
return type.FullName + "." + attributeName;
}
return type.FullName + "." + propertyName + "." + attributeName;
}
private static TReturn GetValue<TAttribute, TReturn>(this Type type, Func<TAttribute, TReturn> attributeValueAction, string name)
where TAttribute : Attribute
{
TAttribute attribute = default(TAttribute);
if (string.IsNullOrEmpty(name))
{
attribute = type.GetCustomAttribute<TAttribute>(false);
}
else
{
var propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
attribute = propertyInfo.GetCustomAttribute<TAttribute>(false);
}
else
{
var fieldInfo = type.GetField(name);
if (fieldInfo != null)
{
attribute = fieldInfo.GetCustomAttribute<TAttribute>(false);
}
}
}
return attribute == null ? default(TReturn) : attributeValueAction(attribute);
}
#endregion
}
调用扩展方法
//获取类名
var className = typeof(User).GetCustomAttributeValue<CustomAttribute, string>(x => x.Custom);
//获取属性中的自定义Attribute
var customAttrVal = typeof(User).GetCustomAttributeValue<CustomAttribute, string>(x => x.Custom, "Id");
//获取内置的Description Attribute
var descVal = typeof(User).GetCustomAttributeValue<DescriptionAttribute, string>(x => x.Description);