• C#基础之特性


    官网地址:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection

        /// <summary>
        /// 使用特性,可以有效地将元数据或声明性信息与代码(程序集、类型、方法、属性等)相关联。 将特性与程序实体相关联后,可以在运行时使用反射这项技术查询特性
        /// </summary>
        /// 
        [System.AttributeUsage(System.AttributeTargets.Class|System.AttributeTargets.Struct,AllowMultiple = true)]
        public class Author : System.Attribute
        {
            string name;
            public double version;
    
            public Author(string name)
            {
                this.name = name;
                version = 1.0;
            }
    
            public string GetName()
            {
                return name;
            }
        }
    
        // Class with the Author attribute.  
        [Author("P. Ackerman")]
        public class FirstClass
        {
            // ...  
        }
    
        // Class without the Author attribute.  
        public class SecondClass
        {
            // ...  
        }
    
        // Class with multiple Author attributes.  
        [Author("P. Ackerman"), Author("R. Koch", version = 2.0)]
        public class ThirdClass
        {
            // ...  
        }
    
        class TestAuthorAttribute
        {
           public  static void Test()
            {
                PrintAuthorInfo(typeof(FirstClass));
                PrintAuthorInfo(typeof(SecondClass));
                PrintAuthorInfo(typeof(ThirdClass));
            }
    
            private static void PrintAuthorInfo(System.Type t)
            {
                System.Console.WriteLine("Author information for {0}", t);
                System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);
                foreach(System.Attribute attr in attrs)
                {
                    if(attr is Author)
                    {
                        Author a = (Author)attr;
                        System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
                    }
                }
            }
        }

    查看官网复习一下相关概念,随手记录一下,以便以后翻阅

     

  • 相关阅读:
    排序算法整理
    V-REP Plugin 开发
    YAML-CPP
    YAML
    V-REP Remote API
    V-REP Plugin
    结构化方法与面向对象方法的比较
    敏捷软件开发vs传统软件工程
    个人项目-地铁出行路线规划程序
    Week1个人作业
  • 原文地址:https://www.cnblogs.com/marshhu/p/11820444.html
Copyright © 2020-2023  润新知