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

    结果:

    待续

  • 相关阅读:
    c#实现windows远程桌面连接程序
    基于.NET平台常用的框架整理
    c#无限循环线程如何正确退出
    c# 内存的具体表现- 通用类型系统 深拷贝 浅拷贝 函数传参
    coco2d-x convertToWorldSpace介绍
    Effective C++条款20:宁以pass-by-reference-to-const替换pass-by-value。Test code
    函数指针与指针函数返回值的区别
    游戏开发那些事
    lua 根据指定字符拆分table字符串(转载)
    实习和学习的双重压力
  • 原文地址:https://www.cnblogs.com/Transmuter/p/11282931.html
Copyright © 2011-2022 走看看