C#中的Attribute(特性)的使用

2021/11/16 17:11:11

本文主要是介绍C#中的Attribute(特性)的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

#define DEBUG
using System.Diagnostics;

namespace Attribute
{
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //Function1();
            HelpAttribute helpAttribute;

            foreach (var attr in typeof(AnyClass).GetCustomAttributes(true))
            {
                helpAttribute = attr as HelpAttribute;
                if (null != helpAttribute)
                {
                    Console.WriteLine("AnyClass Name: {0}",
                        helpAttribute.Name);
                    Console.WriteLine("AnyClass Description: {0}",
                        helpAttribute.Description);                
                }

            }

            Console.ReadLine();
        }

        [Obsolete("Don't use Old Method!", true)] // 表示方法已经过时了,不推荐使用,第二个参数 是否提示报错
        static void Function1()
        {
            MyClass.Message("In Function1");
            Function2();
        }

        static void Function2()
        {
            MyClass.Message("In Function2");
        }
    }

    // value type, System.Type, object, enum
    [Help("this is a do-nothing class", Name = "Jikexueyuan")]
    public class AnyClass
    {
    
    }

    // AllowMultiple 是否可以放多次
    // Inherited 是否可以继承
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public class HelpAttribute : Attribute
    {
        private string description;

        public HelpAttribute(string description)
        {
            this.description = description;
        }

        public string Description { get => description; }

        public string Name
        {
            get;
            set;
        }
    }

    public class MyClass
    {
        [Conditional("DEBUG")]
        public static void Message(string msg)
        {
            Console.WriteLine(msg);
        }
    }
}



这篇关于C#中的Attribute(特性)的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程