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; }
        }
    }    

    结果:

    待续

  • 相关阅读:
    python中将汉字转换成拼音
    关于拉格朗日和内维尔插值算法的python实现
    hdoj1874 (优先队列+Dijkstra)
    hdoj1325 Is It A Tree?
    poj2299 二分思想
    nyoj89 汉诺塔(二)
    nyoj914Yougth的最大化(二分搜索 + 贪心)
    nyoj832 合并游戏(状态压缩DP)
    zoj2432 hdoj1423 最长公共上升子序列(LCIS)
    poj1308 Is It A Tree?(并查集)详解
  • 原文地址:https://www.cnblogs.com/Transmuter/p/11282931.html
Copyright © 2011-2022 走看看