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);
                }
            }
        }
    }

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

 

猜你喜欢

转载自www.cnblogs.com/marshhu/p/11820444.html