NET 特性(Attribute)

时间:2019-08-20
本文章向大家介绍NET 特性(Attribute),主要包括NET 特性(Attribute)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

NET 特性(Attribute)

转自 博客园(Fish)

特性(Attribute):是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。

您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。

特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。

.Net 框架提供了两种类型的特性:预定义特性和自定义特性。

1.自定义特性:Net 框架允许创建自定义特性,用于存储声明性的信息,且可在运行时被检索。该信息根据设计标准和应用程序需要,可与任何目标元素相关。

创建并使用自定义特性包含四个步骤:

  • 声明自定义特性
  • 构建自定义特性
  • 在目标程序元素上应用自定义特性
  • 通过反射访问特性
/// <summary>
    /// 别名特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
    public class AliasAttribute : Attribute
    {
        /// <summary>
        /// 别名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 别名类型
        /// </summary>
        public Type Type { get; set; }

        /// <summary>
        /// 别名名称,类型默认为string
        /// </summary>
        /// <param name="name"></param>
        public AliasAttribute(string name)
        {
            Name = name;
            Type = typeof(string);
        }

        /// <summary>
        /// 别名名称,类型为传入类型
        /// </summary>
        /// <param name="name"></param>
        public AliasAttribute(string name, Type type)
        {
            Name = name;
            Type = type;
        }
    }

2.在目标程序元素上应用自定义特性

public class UserDto
    {
        /// <summary>
        /// 姓名
        /// </summary>
        [Alias("name", typeof(string))]
        public string Name { get; set; }

        /// <summary>
        /// 电话
        /// </summary>
        [Alias("phone", typeof(string))]
        public string Phone { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        [Alias("remark", typeof(string))]
        public string Remark { get; set; }
    }

3.通过反射访问特性

            //  获取type
            var userType = typeof(UserDto);
            //  获取类中所有公共属性集合
            var PropertyArr = userType.GetProperties();
            foreach (var itemProperty in PropertyArr)
            {
                //  获取属性上存在AliasAttribute的数组
                var customAttributesArr = itemProperty.GetCustomAttributes(typeof(AliasAttribute), true);
                if (customAttributesArr.Any())
                {
                    //  获取特性
                    var first = customAttributesArr.FirstOrDefault();
                }
                else {
                    //  不存在特性
                }
            }

原文地址:https://www.cnblogs.com/Study-Csharp/p/11383951.html