zoukankan      html  css  js  c++  java
  • 一些关于c#的特性相关的知识

    1.Conditional 忽略标签

    在某个类的某个方法上面打上标签,那么那个方法在被执行的时候就会被忽略。

    [Conditional("string")]

    下面给出例子

    class Program
    {
            static void Main(string[] args)
            {
                ClassA a = new ClassA();
                a.TestMethodA();
            }
    
            public class ClassA
            {
                public int number = 0;
                [Conditional("eeee")]//忽略
                public void TestMethodA()
                {
                    Console.WriteLine("TestMethodA");
                }
            }
    }

    运行结果:

    如果在程序的最上面加上预编译指令的话,是可以让他像正常一样继续运行的。

    注意,预编译指令一定要放在程序的最最上面。

    例子:

    运行结果:

    2.Obsolete 过时方法提醒标签

    在调用类或者方法上方加上的时候,放上标签就会提示“[弃用的]xxxxx”,作用就是提示,强行调用不会报错,会有绿色曲线提示,强迫症表示很难受。

    例子:

    [Obsolete("别用这个方法了")]
    public void TestMethodB()
    {
        Console.WriteLine("TestMethodB");
    }

    3.自定义特性

    直接上代码:

    using System;
    using System.Reflection;
    
    
    class Program
    {
        static void Main(string[] args)
        {
            Student a = new Student()//实例化的类
            {
                Age = 1,
                Name = "小明"
            };
    
            Type type = typeof(Student);
            foreach (PropertyInfo m in type.GetProperties())
            {
                foreach (Attribute ab in m.GetCustomAttributes(true))
                {
                    //访问成员特性上的信息
                    AttributeTest dbi = (AttributeTest)ab;
                    if (null != dbi)
                    {
                        Console.WriteLine(dbi.Tips);
                    }
                }
            }
        }
    
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property)]//设置该特性用于类还是方法
        public class AttributeTest : Attribute
        {
            public AttributeTest(string tips)
            {
                Tips = tips;
            }
            public string Tips { get; set; }
        }
    
        [AttributeTest("学生类")]
        public class Student
        {
            [AttributeTest("年龄")]
            public int Age { get; set; }
    
            [AttributeTest("名字")]
            public string Name { get; set; }
        }
    }    

    结果:

    待续

  • 相关阅读:
    Vijos P1459 车展 (treap 任意区间中位数)
    「BZOJ1691」[Usaco2007 Dec] 挑剔的美食家 (Treap)
    hdu 1540 Tunnel Warfare(Treap)
    hdu 2844 Coins (多重背包+二进制优化)
    hdu 2159 FATE (二维完全背包)
    hdu 2955 Robberies (01背包)
    hdu 2546 饭卡 (01背包)
    hdu 2191 (多重背包二进制优化)
    2019西北工业大学程序设计创新实践基地春季选拔赛 I Chino with Rewrite (并查集+树链剖分+线段树)
    CF895E Eyes Closed (期望)
  • 原文地址:https://www.cnblogs.com/Transmuter/p/11282931.html
Copyright © 2011-2022 走看看