C# 使用表达式树获取特性的值
作者:互联网
一、定义特性
/// <summary>
/// 定义特性
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false)]
public class DataMember : Attribute
{
public string Name { get; set; }
public string Type { get; set; }
}
二、创建工具类
利用泛型类得知要获取那个类上成员特性的类型,这样就能用Lambda表达式了。Expression.Body读取时是 System.Linq.Expressions.PropertyExpression 类型,找不到断点中Member属性。所以需要转换成 System.Linq.Expressions.MemberExpression 类型
/// <summary>
/// 获取特性工具类
/// </summary>
/// <typeparam name="T"></typeparam>
public static class AttrTool<T>
{
/// <summary>
/// 获取特性Name属性
/// </summary>
/// <typeparam name="Result"></typeparam>
/// <param name="expression"></param>
/// <returns></returns>
public static string DataMemberName<Result>(Expression<Func<T, Result>> expression)
{
var body = expression.Body as MemberExpression;
var attr = body.Member.CustomAttributes.FirstOrDefault(t => t.AttributeType == typeof(DataMember));
var property = attr.NamedArguments.FirstOrDefault(t => t.MemberName == "Name");
return property.TypedValue.Value.ToString();
}
/// <summary>
/// 获取特性Type属性
/// </summary>
/// <typeparam name="Result"></typeparam>
/// <param name="expression"></param>
/// <returns></returns>
public static string DataMemberType<Result>(Expression<Func<T, Result>> expression)
{
var body = expression.Body as MemberExpression;
var attr = body.Member.CustomAttributes.FirstOrDefault(t => t.AttributeType == typeof(DataMember));
var property = attr.NamedArguments.FirstOrDefault(t => t.MemberName == "Type");
return property.TypedValue.Value.ToString();
}
}
三、定义测试模型及调用
/// <summary>
/// 测试模型
/// </summary>
public class AttrModel
{
[DataMember(Name = "this is Test", Type = "string")]
public string Name { get; set; }
}
static void Main(string[] args)
{
var res1 = AttrTool<AttrModel>.DataMemberName(t => t.Name);
var res2 = AttrTool<AttrModel>.DataMemberType(t => t.Name);
Console.WriteLine(res1);
Console.WriteLine(res2);
Console.ReadLine();
}
结果:
标签:FirstOrDefault,string,C#,获取,static,var,public,表达式,Name 来源: https://blog.csdn.net/qq395537505/article/details/113641611