zoukankan      html  css  js  c++  java
  • C# AttributeUsage 简单学习

      首先是定义,MSDN上是这样写的:确定可以如何使用自定义属性类。AttributeUsage 是一个可应用于自定义属性定义的属性,自定义属性定义来控制如何应用新属性。

      它可以通过标记的方式来修饰各种成员。下面有一个简单的例子:

    View Code
    class Program {
            static void Main(string[] args) {
                Type t=typeof(Test);
                var student=t.GetCustomAttributes(typeof(StudentAttribute),false);
                foreach(StudentAttribute each in student){
                    Console.WriteLine("Name:{0}",each.Name);
                    Console.WriteLine("Number:{0}",each.Number);
                }
            }
        }
    
        [Student("DK",084832184)]
        [Student("CP",084832326)]
        public class Test{}
    
        [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
        public class StudentAttribute : Attribute {
            public StudentAttribute(string name, int num) {
                this.Name = name;
                this.Number = num;
            }
    
            public string Name { get; set; }
            public int Number { get; set; }
        }

      在上面的例子中,首先用了自定义的特性,然后再用反射来调用这个特性。

      首先在上面的自定义特性时,第一个参数必须是 AttributeTargets 枚举的一个或多个元素。第二个是参数若设为True则返回属性可对单个实体应用多次。第三个参数若设置为True,则该属性可以由从属性化的类派生的类继承。

      然后通过GetCustomAttributes()方法来调用到特性类的内容。

      若还想关注这个东西的性能的话可以参考Attribute操作的性能优化方式

     

  • 相关阅读:
    [atARC088F]Christmas Tree
    [atARC109F]1D Kingdom Builder
    [luogu4259]寻找车位
    [atARC087F]Squirrel Migration
    [atARC087E]Prefix-free Game
    [atARC110F]Esoswap
    [atARC110E]Shorten ABC
    [atARC084D]Small Multiple
    [atARC083F]Collecting Balls
    [hihocoder][Offer收割]编程练习赛49
  • 原文地址:https://www.cnblogs.com/socialdk/p/2759163.html
Copyright © 2011-2022 走看看