• [C#] 语法之Attribute


    在c#中,定义类的成员,可以定义Property称为属性.Attribute就称为特性.

    在FCL中,有内置的Attribute.如:

    Condition[Attribute]:在什么条件可以调用.(只能作用于返回值为void的方法上)

    Obsolete:方法弃用.支持禁用.

    代码1:

    class Program
        {
            static void Main(string[] args)
            {
                Func();
                Console.ReadLine();
            }
    
            [Obsolete("you can use Func to replace this",true)]
            private static void Test()
            {
                Console.WriteLine("noooo");
            }
    
            private static void Func()
            {
                Console.WriteLine("yesss");
            }
        }
        class T
        {
            [Conditional("DEBUG")]
            public static void M(string str)
            {
                Console.WriteLine("Method{0}", str);
            }
        }
    内置Attribute

    自定义Attribute:

    代码2:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
        public class HelpAttribute : Attribute
        {
            public HelpAttribute(string str)
            {
                HelpStr = str;
            }
            public string Name { get; set; }
            public string HelpStr { get; set; }
        }
    自定义Attribute

    AttributeTargets.Class:作用目标只能是类.

    AllowMultiple:是否可以在一个元素上多次作用特性.

    Inherited:当目标被继承时,特性是否也继承.

    反射获取类的Attribute信息:

    代码3:

    class Program
        {
            static void Main(string[] args)
            {
                var attrs = typeof(MyClass).GetCustomAttributes(false);
                for (int i = 0; i < attrs.Length; i++)
                {
                    var attr = attrs[i] as HelpAttribute;
                    if (attr != null) Console.WriteLine(attr.HelpStr + attr.Name);
                }
                Console.ReadLine();
            }
        }
    
        [Help("good", Name = " class")]
        class MyClass
        {
    
        }
    反射获取特性信息
  • 相关阅读:
    易语言常用源码
    ci的数据库地址
    格式化输出php数组
    mysql插入表情问题
    线程、进程与协程2
    线程、进程与协程
    if __name=='__main__"的作用
    动态导入模块
    面向对象补充之方法
    getpass模块
  • 原文地址:https://www.cnblogs.com/neverc/p/4546835.html
Copyright © 2020-2023  润新知