一、定义特性
/// <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();
} }
三、定义测试模型及调用
class Program
{ static void Main(string[] args)
{ var temp = AttrTool<AttrModel>.DataMemberName(t => t.Name);
Console.WriteLine();
}
} /// <summary>
/// 测试模型
/// </summary>
public class AttrModel
{
[DataMember(Name = "this is Test", Type = "string")]
public string Name { get; set; }
}