一些关于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; }
    }
}    

结果:

 

待续

posted on 2019-08-01 15:33  炼金师  阅读(198)  评论(0编辑  收藏  举报

导航