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;
            }
        }
    }
  • 相关阅读:
    [HDU] 1269 迷宫城堡最简单的强连通分支题
    [HDU] 1301 Jungle Roads赤裸裸的最小生成树
    [HDU] 2647 Reward带有贪心算法的拓扑排序
    [HDU] 1181 变形课简单建模后广搜
    【慢慢学Android】:5.短信拦截
    【慢慢学Android】:8.获取所有短信
    ubuntu下设置Android手机驱动
    Win7笔记本变为热点供手机上WiFi
    VS快捷键和小功能
    【慢慢学Android】:11.对话框大全
  • 原文地址:https://www.cnblogs.com/MrHacker/p/3452813.html
Copyright © 2011-2022 走看看