C#笔记——6.反射与特性

反射与特性简介:

元数据

元数据(MetaData)是一种二进制信息,用以对存储在公共语言运行库可移植可执行文件 (PE文件)或存储在内存中的程序进行描述。

在模块或程序集中定义和引用的每个类型和成员都将在元数据中进行说明。

元数据以非特定语言的方式描述在代码中定义的每一类型和成员。元数据存储以下信息:

  • 程序集的说明

        标识(名称、版本、区域性、公钥)。
        导出的类型。
        该程序集所依赖的其他程序集。
        运行所需的安全权限。
    
  • 类型的说明

        名称、可见性、基类和实现的接口。
        成员(方法、字段、属性、事件、嵌套的类型)。
    
  • 属性

        修饰类型和成员的其他说明性元素。
    

特性

特性(Attribute)是用于在运行时传递程序中在代码中定义的每一类型和成员的行为信息的声明性标签。

可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。

.Net 框架提供了两种类型的特性:预定义特性和自定义特性。

反射

反射(Reflection)是指程序可以访问、检测和修改它本身状态或行为的一种能力。

可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。

常用预定义特性

ObsoleteAttribute 类

命名空间: System
程序集: mscorlib(位于 mscorlib.dll)

继承层次结构
System.Object
  System.Attribute
    System.ObsoleteAttribute

主要作用:标记不再使用的程序元素。 此类不能被继承。

构造函数:

    [Obsolete()]

    [Obsolete(message)]

    [Obsolete(
    message,
    iserror
    )]

参数 message
是一个字符串,描述项目为什么过时的原因以及该替代使用什么。
参数 iserror
是一个布尔值。如果该值为 true,编译器应把该项目的使用当作一个错误。默认值是 false(编译器生成一个警告)。

ConditionalAttribute 类

命名空间: System.Diagnostics
程序集: mscorlib(位于 mscorlib.dll)

继承层次结构
System.Object
  System.Attribute
    System.Diagnostics.ConditionalAttribute

主要作用:指示编译器,除非定义了指定的有条件编译符号,否则,应忽略方法调用或属性。

构造函数:

[Conditional(conditionalSymbol)]


//例如常用的

[Conditional("DEBUG")]

测试代码:

#define DEBUG
using System;

using System.Diagnostics;

namespace AttributeTest{

    public class Myclass
    {
        [Conditional("DEBUG")]
        public static void Message(string msg)
        {
            Console.WriteLine(msg);
        }
    }

    class Test
    {
        static void function1()
        {
            Myclass.Message("In Function 1.");
            function2();
        }
        static void function2()
        {
            Myclass.Message("In Function 2.");
        }
        public static void Main()
        {
            Myclass.Message("In Main function.");
            function1();
            Console.ReadKey();
        }
    }
}

只有在程序集中定义相应的指定的有条件编译符号,才会执行该特性修饰的方法或属性;否则,忽略方法调用或属性。即#define DEBUG

DllImportAttribute 类

命名空间: System.Runtime.InteropServices
程序集: mscorlib(位于 mscorlib.dll)

继承层次结构
System.Object
  System.Attribute
    System.Runtime.InteropServices.DllImportAttribute

主要作用:指示由非托管动态链接库 (DLL) 公开为静态入口点的特性化方法。

DllImport代码案例:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace ServerTools
{
    public class ConsoleUtil
    {
        /// <summary>
        /// 回调函数委托原型
        /// </summary>
        /// <param name="ctrlType"></param>
        /// <returns></returns>
        public delegate bool CtrlHandlerDelegate(int ctrlType);

        /// <summary>
        /// 导入系统核心库文件,声明外部导入函数SetConsoleCtrlHandler(callback , isAdd)
        /// </summary>
        /// <param name="callback">控制台发出关闭信息后的回调函数</param>
        /// <param name="isAdd">是否添加该回调</param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        public static extern bool SetConsoleCtrlHandler(CtrlHandlerDelegate callback , bool isAdd);

        bool CtrlHandler(int ctrlType)
        {
            switch(ctrlType)
            {

                case 0:
                    Console.WriteLine("程序被强制关闭,按任意键退出");
                    //Do Something
                    Console.ReadKey(false);
                    break;
                case 2:
                    Console.WriteLine("程序被强制关闭,按任意键退出");
                    //Do Something
                    Console.ReadKey(false);
                    break;
                case 4:
                    Console.WriteLine("程序被强制关闭");
                    //Do Something
                    break;
            }
            return false;
        }

        public void RegisterCtrlHandler()
        {
            SetConsoleCtrlHandler(CtrlHandler,true);
        }
    }
}

调用代码:

    ConsoleUtil consoleUtil = new ConsoleUtil();
    consoleUtil.RegisterCtrlHandler();

SerializableAttribute类

参考下一笔记,序列化和反序列化

AttributeUsageAttribute 类

命名空间: System
程序集: mscorlib(位于 mscorlib.dll)

继承层次结构
System.Object
  System.Attribute
    System.AttributeUsageAttribute

主要作用:预定义特性类 AttributeUsage 描述了如何使用一个自定义特性类。它规定了特性可应用到的项目的类型。

构造函数:

[AttributeUsage(
   validon,
   AllowMultiple=allowmultiple,
   Inherited=inherited
)]

//例如如下使用方式:

[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

参数 validon
规定特性可被放置的语言元素。它是枚举器 AttributeTargets 的值的组合。默认值是 AttributeTargets.All。

参数 allowmultiple(可选的)
为该特性的 AllowMultiple 属性(property)提供一个布尔值。如果为 true,则该特性是多用的。默认值是 false(单用的)。

参数 inherited(可选的)
为该特性的 Inherited 属性(property)提供一个布尔值。如果为 true,则该特性可被派生类继承。默认值是 false(不被继承)。

自定义特性

反射

REF

深入理解C#、C#高级编程、C#游戏脚本编程

原文地址:https://www.cnblogs.com/sylvan/p/9164191.html