zoukankan      html  css  js  c++  java
  • C# 特性(attribute)

    Atrribute表示自定义特性的基类。

    其派生类约定惯例以Attribute结尾命名,如:AttributeUsageAttribute、TestAttribute。

    下面获取如何定制特性attribute和获取自定义特性信息:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace AttributeDemo
    {
        [Test("it's a class1")]
        [Test("it's a class2")]
        [Test("it's a class3")]
        class Program
        {
            [Test("it's a property")]
            public String Name { get; set; }
    
            static void Main(string[] args)
            {
                Program p = new Program();
    
                Type type = typeof(Program);
                MethodInfo method = type.GetMethod("AttributeTest");
                MemberInfo member = type.GetMember("Name").First();
    
                //利于反射分别获取类、方法、属性的算定义特性实例化
                TestAttribute[] myAttr = (TestAttribute[])Attribute.GetCustomAttributes(type, typeof(TestAttribute));
                TestAttribute myAttr2 = (TestAttribute)Attribute.GetCustomAttribute(method, typeof(TestAttribute));
                TestAttribute myAttr3 = (TestAttribute)Attribute.GetCustomAttribute(member, typeof(TestAttribute));
    
                foreach (TestAttribute attr in myAttr)
                {
                    Console.WriteLine(attr.Message);//输出类Program的自定义特性
                }
                Console.WriteLine(myAttr2.Message); //输出方法AttributeTest的自定义特性
    
                Console.WriteLine(myAttr3.Message); //输出属性Name的自定义特性
    
                //调用方法AttributeTest
                object obj = Activator.CreateInstance(typeof(Program));
                method.Invoke(obj, null);
    
                
            }
    
            [Test("it's a method")]
            public void AttributeTest()
            {
                Console.WriteLine("我还可以这样被调用");
            }
        }
    
        [AttributeUsageAttribute(AttributeTargets.All,AllowMultiple=true,Inherited=true)]
        public class TestAttribute : Attribute
        {
            public String Message { get; set; }
            public TestAttribute(string message)
            {
                this.Message = message;
            }
        }
    }
  • 相关阅读:
    基元线程同步构造之用户模式易变构造volatile
    C# 基元线程同步构造
    idea 的Low Memory问题
    python工具——xmind
    VSCODE 远程开发树莓派
    firefox临时文件位置及修改方法
    Veeam Backup & Replication 9.5 备份方式详解
    Windows下登录凭证密码获取工具
    VMProtect虚拟机保护分析入门
    Applescrip
  • 原文地址:https://www.cnblogs.com/MrHacker/p/3452813.html
Copyright © 2011-2022 走看看