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;
            }
        }
    }
  • 相关阅读:
    Golang调用windows下的dll动态库中的函数
    Golang 编译成 DLL 文件
    go 通过nginx代理后获取用户ip
    idea教程--Maven 骨架介绍
    idea教程--快速插入依赖
    Java开发名词解释
    Android Studio安装
    Java基础--Eclipse关联Java源码
    【排序基础】3、随机生成排序算法 测试用例
    【排序基础】2、使用模板(泛型)编写选择排序算法
  • 原文地址:https://www.cnblogs.com/MrHacker/p/3452813.html
Copyright © 2011-2022 走看看