zoukankan      html  css  js  c++  java
  • 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();
        }
    
    }

    三、定义测试模型及调用

    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; }
    }
  • 相关阅读:
    经济危机下,自主创业已成为一种时代潮流?
    曾靖雯(帮别人名字作诗)
    四大内伤造就80后创业高失败率
    如何让创业的路不再崎岖
    叶莉(帮别人名字作诗)
    谁能够在萧条中生存?历史总是惊人相似的(转)
    哪种书最适合创业者阅读
    中西部崛起 关键是要激发普遍的创业热情
    每日英语:Dating in China Is a Largely Commercial Transaction
    每日英语:Poor Chinese Schools Tell Students: Bring Your Own Desks
  • 原文地址:https://www.cnblogs.com/haosit/p/10904913.html
Copyright © 2011-2022 走看看