C#知识学习-反射和特性

4 篇文章 0 订阅

反射

可以通过 type来获取类的信息(名字,所在命名空间,所在的程序集,有哪些字段,属性,方法等)

using System.Reflection;//反射要调用的命名空间
Type type = myClass.GetType();//获取一个类的Type
FieldInfo[] array1 = type.GetFields();//获取type中的所有字段名
PropertyInfo[] array2 = type.GetProperties();//获取type中的所有属性名
MethodInfo[] array3 = type.GetMethods();//获取type中的所有方法名

特性

[Obsolete("使用新方法代替")]//表示方法已被弃用
        static void OldMethod()
        {
            ....
        }
[Conditional("IsTest")]//需要命名空间System.Diagnostics 若没有定义字符串中的宏,则方法不会被调用
        void Test()
        {
            ....
        }

调用者信息特性

需要命名空间System.Runtime.CompilerServices

可以输出文件路径名,代码行数,调用的方法名

public static void PrintOut(string message,[CallerFilePath] string fileName = ""  ,[CallerLineNumber]int lineNumber=0,[CallerMemberName]string MemberName="")
        {
            Console.WriteLine(message);
            Console.WriteLine(fileName);
            Console.WriteLine(lineNumber);
            Console.WriteLine(MemberName);
        }

自定义特性

  1. 特性类后缀以Attribute结尾
  2. 需要继承自System.Attribute
  3. 一般情况下声明为sealed(表示无法被继承的)
  4. 一般情况下特性类用来表示目标结构的一些状态
using System.Attribute;

[AttributeUsage(AttributeTargets.Class)]//表示该特性类可以应用的程序结构有哪些 这里选择了类类型
    sealed class MyTestAttribute : Attribute
    {
        public string Des { get; set; }
        public string VersionNumber { get; set; }
        public int ID { get; set; }
        public MyTestAttribute(string des)
        {
            this.Des = des;
        }
    }
....
[MyTest("特性类",ID =100)]
    class Program
....
Type type = typeof(Program);
            Object[] array = type.GetCustomAttributes(false);//获取该type的所有特性
            MyTestAttribute myTest = array[0] as MyTestAttribute;
            Console.WriteLine(myTest.Des+" "+myTest.ID);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值