C#中的反射

本文全面介绍了.NET反射的基础知识及高级应用,包括如何获取类型信息、使用Type类的属性和方法,以及动态加载程序集和晚期绑定等。通过实例演示了反射在.NET应用程序中的强大功能。

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

http://www.codeproject.com/Articles/55710/Reflection-in-NET#_Toc252700542

Introduction

In this article, I have tried to cover all the topics from .NET Reflection with examples. I have stated with the definition of .NET Reflection and its road map, a list of mostly used classes the System.Reflection namespace provides, and the importance of the Type class in .NET Reflection. You will also learn how to get the type information using different ways. Use of properties and methods of the Type class in .NET Reflection, with examples, are explained in this article. You will also see advanced Reflection topics like dynamically loading an assembly and late binding, at the end of this article.

stated 规定(state的过去分词);陈述;阐明

What is .NET Reflection?

.NET Framework's Reflection API allows you to fetch type (assembly) information at runtime programmatically. We can also achieve late binding by using .NET Reflection.

At runtime, the Reflection mechanism uses the PE file to read information about the assembly. Reflection enables you to use code that is not available at compile time.

.NET Reflection allows an application to collect information about itself and also to manipulate on itself. It can be used effectively to find all types in an assembly and/or dynamically invoke methods in an assembly.

This includes information about the type, properties, methods, and events of an object. With Reflection, we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. We can also access attribute information using Reflection.

Using Reflection, you can get any kind of information which you can see in a class viewer; for example, information on the methods, properties, fields, and events of an object.

manipulate 操纵;操作;巧妙地处理;篡改

attribute  属性;特质

The System.Reflection namespace and the System.Type class plays a very important role in .NET Reflection. These two work together and allow you to reflect over many other aspects of a type.

 

 

Road Map

The System.Reflection Namespace

The System.Reflection namespace contains the classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types;

this process is known as Reflection in .NET framework. We will take a look at some of the commonly used classed here:

ClassDescription
AssemblyRepresents an assembly, which is a reusable, versionable, and self-describing building block of a Common Language Runtime application. This class contains a number of methods that allow you to load, investigate, and manipulate an assembly.
ModulePerforms Reflection on a module. This class allows you to access a given module within a multi-file assembly.
AssemblyNameThis class allows you to discover numerous details behind an assembly's identity. An assembly's identity consists of the following:
  • Simple name
  • Version number
  • Cryptographic key pair
  • Supported culture
EventInfoThis class holds information for a given event. Use the EventInfo class to inspect events and to bind to event handlers.
FieldInfoThis class holds information for a given field. Fields are variables defined in the class.FieldInfo provides access to the metadata for a field within a class, and provides dynamic set and get functionality for the field. The class is not loaded into memory until Invoke orget is called on the object.
MemberInfoThe MemberInfo class is the abstract base class for classes used to obtain information about all members of a class (constructors, events, fields, methods, and properties).
MethodInfoThis class contains information for a given method.
ParameterInfoThis class holds information for a given parameter.
PropertyInfoThis class holds information for a given property.

investigate 调查;研究

Before we start using Reflection, it is necessary to understand the System.Type class.

In order to continue with all the examples given in this article, I am using a Car class as an example. It will look like this:

 

 

The System.Type Class

The System.Type class is the main class for the .NET Reflection functionality and is the primary way to access metadata. The System.Type class is an abstract class and represents a type in the Common Type System (CLS).

It represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.

Use the members of Type to get information about a type declaration, such as the constructors, methods, fields, properties, and events of a class, as well as the module and the assembly in which the class is deployed.

There are tree ways to obtain a Type reference:

 

Using System.Object.GetType()

This method returns a Type object that represents the type of an instance. Obviously, this approach will only work if you have compile-time knowledge of the type.

obviously 明显地 

compile-time 编译时

static void ObjectGetType()
        {
            Car car = new Car();
            Type type = car.GetType();
            Console.WriteLine(type.FullName);
            Console.WriteLine();
        }

 

Using System.Type.GetType()

Another way of getting type information in a more flexible manner is the GetType() static method of the Typeclass which gets the type with the specified name, performing a case-sensitive search.

Type.GetType() is an overloaded method that accepts the following parameters:

  1. fully qualified string name of the type you are interested in examining
  2. exception that should be thrown if the type cannot be found
  3. establishes the case sensitivity of the string

case sensitivity区分大小写

 static void TypeGetType()
        {
            string typeName = "Reflection.DemoCar";
            Type type = Type.GetType(typeName, false, true);
            ConsoleResult(type, typeName);

            typeName = "ReflectionDemo.Car";
            type = Type.GetType(typeName, false, true);
            ConsoleResult(type, typeName);
            Console.WriteLine();
        }

        static void ConsoleResult(Type type,string typeName)
        {
            if (type != null)
            {
                Console.WriteLine(type.FullName);
            }
            else
            {
                Console.WriteLine("Can not find the type {0}", typeName);
            }
        }

 

Using the typeof () C# Operator

The final way to obtain type information is using the C# typeof operator. This operator takes the name of the type as a parameter.

static void TypeOfOperator()
        {
            Type type = typeof(Car);
            Console.WriteLine(type.FullName);
            Console.WriteLine();
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值