C# 学习——反射和特性

本文深入探讨C#中的反射机制,解释如何通过Type类获取类的元数据信息,如名称、命名空间、程序集及字段、属性和方法。同时,介绍了系统内置的Obsolete和Conditional特性,以及自定义特性的创建和使用方法,展示了如何增强代码的元数据和可扩展性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

反射

程序在运行时,可以查看其它程序集或者本身的元数据的行为叫做反射。BCL声明了一个叫做Type的抽象类,它被设计用来包含类型的特性。使用这个类的对象能让我们获取程序使用的类型信息。
以下是System.Type类部分成员信息

  • Name:返回类型的名字

  • NameSpace:返回包含类型声明的命名空间

  • Assembly:放回声明类型的程序集

    • Assembly.FullName:获取程序集的全名
    • GetTypes():获取程序集中定义的类型
    • GetCustomAttributes():获取特性
  • GetFields:返回类型的字段列表

  • GetProperties:返回类型的属性列表

  • GetMethods:返回类型的方法

           //每个类,对应一个Type对象,存储了类的成员和方法
            MyClass my = new MyClass();
            Type type = my.GetType();//通过对象获取对象所属的Type对象
            Console.WriteLine(type.Name);//获取类的名字
            Console.WriteLine(type.Namespace);//获取类的命名空间
            Console.WriteLine(type.Assembly);//获取类所在的程序集
            Console.WriteLine("-----------GetFields--------------");
            var fields=type.GetFields();//只能获取Public字段
            for (int i = 0; i < fields.Length; i++)
            {
                Console.Write(fields[i].Name + " ");
            }
            Console.WriteLine("");
            Console.WriteLine("-----------GetProperties--------------");
            var properties = type.GetProperties();//获取Public属性
            for (int i = 0; i < properties.Length; i++)
            {
                Console.Write(properties[i].Name + " ");
            }
            Console.WriteLine("");
            Console.WriteLine("-----------GetMethods--------------");
            var methods = type.GetMethods();//获取Public方法
            for (int i = 0; i < methods.Length; i++)
            {
                Console.Write(methods[i].Name + " ");
            }
            Console.WriteLine("");
            ///通过Type可以获取到类中public(公有)的字段、属性以及方法
            Assembly assembly = my.GetType().Assembly;//获取当前程序集
            Console.WriteLine("Current Assembly = " + assembly.FullName);
            Console.WriteLine("");
            Console.WriteLine("-----------Current Assembly All Types--------------");
            var types=assembly.GetTypes();//当前程序集下所有的类型
            foreach (var info in types)
            {
                Console.Write(info.Name +" ");
            }
            Console.WriteLine("");
输出结果:
MyClass
ConsoleApp
ConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
-----------GetFields--------------
Nick
-----------GetProperties--------------
Name
-----------GetMethods--------------
get_Name set_Name Print ShowMessage GetType ToString Equals GetHashCode
Current Assembly = ConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=
null

-----------Current Assembly All Types--------------
Program GameRole MyClass RoleSkill

特性

特性(attribute)是一种允许我们向程序集增加元数据的语言结构。它是用于保存程序结构信息的某种特殊类型的类。

  • 系统内置的一些特性:

    • Obsolete:将程序结构标注为过期,并且在代码编译时显示有用的警告信息

    • Conditional:包括或取消特定方法的调用,配合宏使用。命名空间为using System.Diagnostics;

      //宏
      //#define IsTest 如果定义了宏,Tes1会调用,否则就不会调用
      //函数代码
      [Conditional("IsTest")]
      static void Test1()
      {
          Console.WriteLine("Test_1");
      }
      
      static void Test2()
      {
          Console.WriteLine("Test_2");
      }
      调用代码:
      static void Main(string[] args)
      {
          Test1();
          Test2();
          Test1();
          Test2();
          Test1();
          Test2();
      }
      未定义宏输出结果:
      Test_2
      Test_2
      Test_2
      
    • 调用者信息特性:调用者可以分别用CallerFilePath,CallerLineNumber,和CallerMemberName可以访问文件路径、代码行数和调用成员的名称等源代码信息

      //#define IsTest
      using System;
      using System.Collections;
      using System.Text;
      using System.Text.RegularExpressions;
      using System.Collections.Generic;
      using System.Linq;
      using System.Reflection;
      using System.Diagnostics;
      using System.Runtime.CompilerServices;
      namespace ConsoleApp
      {
          class Program
          {
              static void Main(string[] args)
              {
                  PrintOut("Test 调用者特性");
              }
      
              public static void PrintOut(string message, [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string callMember = "")
              {
                  Console.WriteLine("Message : " + message);
                  Console.WriteLine("Line : " + lineNumber);
                  Console.WriteLine("File Path : " + fileName);
                  Console.WriteLine("Called From : " + callMember);
              }
          }
      }
      输出结果:
      Message : Test 调用者特性
      Line : 17
      File Path : F:\Net\Project\ConsoleApp\Program.cs
      Called From : Main
      
    • DebuggerStepThrough:告诉调试器在执行目标调试时不要进入该方法调试

  • 自定义特性:特性只是某个特殊结果的类。所有的特性类都派生自System.Attribute,自定义特性类必须继承自System.Attribute。一般情况下特性类不需要被继承,因此特性类一般声明为sealed(禁止继承)

//特性类
[AttributeUsage(AttributeTargets.Class)]//表示该特性类可以使用到的程序结果
    sealed class MyAttribute:System.Attribute
    {
        public MyAttribute(string des)
        {
            this.Description = des;
        }
        public string Description { get; set; }
        public string Version { get; set; }

        public int Id { get; set; }
    }
    ///使用示例
    [My("特性类简单使用", Id = 10001)]//使用特性相当于调用特性类的构造方法
    class MyClass
    {
    }
 //特性使用
   static void Main(string[] args)
        {
            MyClass my = new MyClass();
            var att = my.GetType().GetCustomAttributes();
            foreach (var info in att)
            {
                if (info is MyAttribute)
                {
                    MyAttribute myAttribute = info as MyAttribute;
                    Console.WriteLine(myAttribute.Id);
                }
            }
        }
 //输出结果
 10001
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值