博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 特性demo
阅读量:2026 次
发布时间:2019-04-28

本文共 1718 字,大约阅读时间需要 5 分钟。

using System;using System.Reflection;// An enumeration of animals. Start at 1 (0 = uninitialized).public enum Animal{    // Pets.    Dog = 1,    Cat,    Bird,}// A custom attribute to allow a target to have a pet.public class AnimalTypeAttribute : Attribute{    // The constructor is called when the attribute is set.    public AnimalTypeAttribute(Animal pet)    {        thePet = pet;    }    // Keep a variable internally ...    protected Animal thePet;    // .. and show a copy to the outside world.    public Animal Pet    {        get { return thePet; }        set { thePet = value; }    }}// A test class where each method has its own pet.class AnimalTypeTestClass{    [AnimalType(Animal.Dog)]    public void DogMethod() { }    [AnimalType(Animal.Cat)]    public void CatMethod() { }    [AnimalType(Animal.Bird)]    public void BirdMethod() { }}namespace ConsoleApplication3{    class Program    {        static void Main(string[] args)        {            AnimalTypeTestClass testClass = new AnimalTypeTestClass();            Type type = testClass.GetType();            // Iterate through all the methods of the class.            foreach (MethodInfo mInfo in type.GetMethods())            {                // Iterate through all the Attributes for each method.                foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))                {                    // Check for the AnimalType attribute.                    if (attr.GetType() == typeof(AnimalTypeAttribute))                        Console.WriteLine(                            "Method {0} has a pet {1} attribute.",                            mInfo.Name, ((AnimalTypeAttribute)attr).Pet);                }            }        }    }}

转载地址:http://wtdaf.baihongyu.com/

你可能感兴趣的文章
互联网时代,移动者为王
查看>>
SuperMap房产测绘成果管理平台
查看>>
SuperMap 商品房销售网上备案服务管理平台
查看>>
SuperMap 办公自动化服务平台
查看>>
SuperMap 房产政务协同管理平台
查看>>
CTO和CIO有什么不同
查看>>
LAMP网站架构方案分析
查看>>
苹果CEO乔布斯用人九法则
查看>>
图解windows2008无法使用无线网络的解决方法
查看>>
做CEO的左膀右臂 CTO要看未来10年
查看>>
CTO在企业技术创新中的作用和地位
查看>>
供应链SCOR模型搭建/改进
查看>>
分析:知识经济时代企业CIO职能转变
查看>>
关于开心网的服务器
查看>>
中国科大与中科院数学院全面合作并创办"华罗庚班"
查看>>
开心网(kaixin001.com)服务器架构的一点猜想
查看>>
抓虾网的架构
查看>>
架构设计之性能设计经验
查看>>
淘宝自主研发的系统
查看>>
Web架构设计的几个心得
查看>>