美文网首页c#学习
C# attribute用法

C# attribute用法

作者: 李药师_hablee | 来源:发表于2019-12-25 16:38 被阅读0次

    贴代码

    using System;
    using System.Reflection;
    
    namespace my_attribute
    {
        [AttributeUsage(AttributeTargets.Class
            | AttributeTargets.Method,
            AllowMultiple = true)]
        public class HelpAttribute : System.Attribute
        {
            public readonly string url;
            private string topic;
            public string Topic
            {
                get
                {
                    return topic;
                }
                set
                {
                    topic = value;
                }
            }
            public HelpAttribute(string url)
            {
                this.url = url;
            }
        }
        [HelpAttribute("https://msvc/MyClassInfo", Topic = "Test"),
            Help("https://my.com/about/class")]
        class MyClass
        {
            [Help("http;//my.com/about/method")]
            public void MyMethod()
            {
                return;
            }
        }
        class Program
        {
            static void Main()
            {
                Type myType = typeof(MyClass);
                object[] attributes = myType.GetCustomAttributes(false);
                for (int i = 0; i < attributes.Length; i++)
                    PrintAttributeInfo(attributes[i]);
                MemberInfo[] myMembers = myType.GetMembers();
                for(int i=0;i<myMembers.Length;i++)
                {
                    Console.WriteLine("\nNumber {0}: ", myMembers[i]);
                    object[] myAttributes = myMembers[i].GetCustomAttributes(false);
                    for (int j = 0; j < myAttributes.Length; j++)
                        PrintAttributeInfo(myAttributes[j]);
                }
            }
            static void PrintAttributeInfo(object attr)
            {
                if(attr is HelpAttribute)
                {
                    HelpAttribute attrh = (HelpAttribute)attr;
                    Console.WriteLine("------Url:" + attrh.url + " topic:" + attrh.Topic);
                }
            }
        }
        
    }
    

    相关文章

      网友评论

        本文标题:C# attribute用法

        本文链接:https://www.haomeiwen.com/subject/wzwcoctx.html