Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of reflection in .net

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you the example analysis of reflection in .net, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's learn about it!

Overview of reflection

Type information can be provided through reflection, which enables us developers to use this information to construct and use objects at run time.

The reflection mechanism allows the program to add various functions dynamically during execution.

Runtime type identification

Runtime type identification (RTTI), which determines the object type during program execution. For example, you can use it to know exactly what type of object the base class reference points to.

Run-time type identification, which can pre-test the success of a cast operation, thereby avoiding invalid cast exceptions.

There are three keywords that support RTTI in c #: is, as, and typeof. Let's introduce them in turn.

Is operator:

Through the is operator, you can determine whether the object type is a special top type, and if the two types are the same type, or if there is a reference between the two, the boxing and unboxing conversion indicates that the two types are compatible.

The code is as follows:

View Code

Class Program

{

Static void Main (string [] args)

{

An a = new A ()

B b = new B ()

If (an is A)

{

Console.WriteLine ("an is an A"); / / this print because an is an object of type A.

}

If (b is A)

{

/ / this print, because b is an object of type B, and type B is derived from type A, and because the object b can be converted to type A, the object b is compatible with type A, but the reverse is not true, for example, the following does not print

Console.WriteLine ("b is an A because it is derived from")

}

If (an is B)

{

/ / this does not print

Console.WriteLine ("This won't display, because a not derived from B")

}

If (an is object)

{

/ / this print

Console.WriteLine ("an is an object")

}

Console.ReadKey ()

}

}

Class A {}

Class B: A {}

As operator:

While performing type conversions at run time, and being able to return a null value without throwing an exception when type conversion fails, as can also be seen as a simplified alternative to the is operator (see example).

The copy code is as follows:

View Code

Class Program

{

Static void Main (string [] args)

{

An a = new A ()

B b = new B ()

If (an is B)

{

B = (B) a; / / because the a variable is not of type B, it is invalid to convert the a variable to type B here.

}

Else

{

B = null

}

If (b = = null)

{

/ / this print

Console.WriteLine ("The cast in b = (B) an is not allowed")

}

/ / the above uses the as operator to merge the two into one.

B = the an as B; / / as type first checks the validity of the cast and, if it is valid, performs the strongly typed conversion process. All this is done in this sentence.

If (b = = null)

{

/ / this print

Console.WriteLine ("The cast in b = (B) an is not allowed")

}

Console.ReadKey ()

}

}

Class A {}

Class B: A {}

Typeof operator:

As, is can test the compatibility of the two types. But in most cases, you also need to get some type of specific information. This uses typeof, which returns a System.Type object related to a specific type, and the System.Type object allows you to top up this type of feature. Once you have a Type object of a given type, you can get specific information about the type by using the various properties, fields, and methods defined by the object. The Type class contains many members, which will be discussed in more detail in the following reflection. The following is a simple demonstration of the Type object, calling its three properties.

The copy code is as follows:

View Code

Static void Main (string [] args)

{

Type t=typeof (StringBuilder)

The Console.WriteLine (t.FullName); / / FullName property returns the full name of the type

If (t.IsClass)

{

Console.WriteLine ("is a class"); / / print

}

If (t.IsSealed) / / whether it is a sealed class

{

Console.WriteLine ("is Sealed"); / / print

}

Console.ReadKey ()

}

Core class of reflection: System.Type class

Many classes that support reflection are located in the System.Reflection namespace and are part of the. net Reflection API, so the System.Reflection namespace is generally used in programs that use reflection.

System. The Type class, which wraps types and is therefore the core of the entire reflection subsystem, contains a number of properties and methods that can be used to get type information at run time.

The Type class derives from the System.Reflection.MemberInfo abstract class

Read-only properties in the MemberInfo class

Attribute

Description

Type DeclaringType

Gets the type of the class or interface that declares the member

MemberTypes MemberType

Gets the type of the member, which is used to indicate that the member is a field, method, property, event, or constructor

Int MetadataToken

Get values related to specific metadata

Module Module

Gets a Module object that represents the module (executable) in which the reflection type resides

String Name

Name of the member

Type ReflectedType

Object type of reflection

Attention please

The return type of the MemberType property is MemberTypes, which is an enumeration that defines the type values used to represent different members. These values include: MemberTypes.Constructor, MemberTypes.Method, MemberTypes.Field, MemberTypes.Event, MemberTypes.Property. So you can determine the type of member by checking the MemberType property, for example, when the value of the MemberType property is MemberTypes.Method, the member is a method

The MemberInfo class also contains two abstract methods related to features:

1.GetCustomAttributes (): gets a list of custom properties associated with the tone object.

2.IsDefined (): determines whether the corresponding properties are defined for the host object.

3.GetCustomAttributesData (): returns information about custom properties (which will be mentioned later)

Of course, in addition to the methods and properties defined by the MemberInfo class, the Type class itself has added many properties and methods: as shown in the following table (only some commonly used ones are listed, too many, you can define the Type class to take a look)

Methods defined by the Type class

Method

Function

ConstructorInfo [] GetConstructors ()

Gets a list of constructors of the specified type

EventInfo [] GetEvents ()

Gets the time column of the specified type

FieldInfo [] GetFields ()

Gets the field column of the specified type

Type [] GetGenericArguments ()

Gets a list of type parameters bound to the constructed generic type, and gets the type parameter if the generic type definition of the specified type is specified. For types constructed early, the list may contain both type arguments and type parameters

MemberInfo [] GetMembers ()

Gets a list of members of the specified type

MethodInfo [] GetMethods ()

Gets a list of methods of the specified type

PropertyInfo [] GetProperties ()

Gets a list of properties of the specified type

The following lists the commonly used read-only properties defined by the Type class

Properties defined by the Type class

Attribute

Function

Assembly Assembly

Gets the assembly of the specified type

TypeAttributes Attributes

Get the properties of a defined type

Type BaseType

Gets the direct base type of the specified type

String FullName

Gets the full name of the specified type

Bool IsAbstract

Returns true if the specified type is abstract

Bool IsClass

Returns true if the specified type is a class

String Namespace

Gets the namespace of the specified type

Use reflection

The above techniques are all for the use here.

By using the methods and properties defined by the Type class, we can get various specific information about the type at run time. This is a very powerful feature. Once we have the type information, we can call its constructors, methods, and properties. As you can see, reflection allows the use of code that is not available at compile time.

Because there are so many Reflection API, it is impossible to introduce them completely here (if a complete introduction here, it is said to want a book, a thick book). However, Reflection API is designed according to a certain logic. Therefore, as long as you know how to use some of the interfaces, you can use the remaining interfaces by analogy.

Here I list four key reflection technologies:

1. Get information about the method

two。 Call method

3. Construction object

4. Load types from an assembly

Get information about the method

Once you have the Type object, you can use the GetMethodInfo () method to get a list of methods supported by this type. This method returns an array of MethodInfo objects, the MethodInfo object describing the methods supported by the tone type, which is in the System.Reflection namespace

The MethodInfo class is derived from the MethodBase abstract class, while the MethodBase class inherits the MemberInfo class. So we can use the properties and methods defined by these three classes. For example, use the Name property to get the method name. There are two important members:

1. ReturnType property: an object of type Type, which provides the return type information of the method.

2. The GetParameters () method returns a list of parameters, and the parameter information is stored in the PatameterInfo object as an array. The PatameterInfo class defines a large number of properties and methods that describe parameter information. Two commonly used attributes are also listed here: Name (a string containing parameter name information) and ParameterType (parameter type information).

In the following code, I will use reflection to get the methods supported in the class, as well as the method information.

The copy code is as follows:

View Code

Class MyClass

{

Int x

Int y

Public MyClass (int I, int j)

{

X = I

Y = j

}

Public int sum ()

{

Return x + y

}

Public bool IsBetween (int I)

{

If (x < I & & I < y) return true

Else return false

}

Public void Set (int a, int b)

{

X = a

Y = b

}

Public void Set (double a, double b)

{

X = (int) a

Y = (int) b

}

Public void Show ()

{

Console.WriteLine ("x: {0}, y: {1}", xQuery)

}

}

Class ReflectDemo

{

Static void Main (string [] args)

{

Type t=typeof (MyClass); / / get the Type object that describes the MyClass type

Console.WriteLine ("Analyzing methods in" + t.Name); / / t.name = "MyClass"

MethodInfo [] mi = t.GetMethods (); / / the MethodInfo object is under the System.Reflection namespace.

Foreach (MethodInfo m in mi) / / traverses an array of mi objects

{

Console.Write (m.ReturnType.Name); / / returns the return type of the method

Console.Write ("" + m.Name + "("); / / returns the name of the method

ParameterInfo [] pi = m.GetParameters (); / / get the method parameter list and save it in the ParameterInfo object array

For (int I = 0; I < pi.Length; iTunes +)

{

Console.Write (Pi [I] .ParameterType.Name); / / the parameter type name of the method

Console.Write ("" + Pi [I] .Name); / / the parameter name of the method

If (I + 1 < pi.Length)

{

Console.Write (,)

}

}

Console.Write (")")

Console.WriteLine (); / / Line feeds

}

Console.ReadKey ()

}

}

The output is: Analyzing methods inMyClass MyClass (int I, int j) int sum () bool IsBetween (int I) void Set (int a, int b) void Set (double a, double b) void Show ()

Bool Equals (object obj) int GetHashCode () Type GetType () string ToString ()

Note: in addition to all the methods defined by the MyClass class, the output here also shows the common non-static methods defined by the object class. This is because all types in c # inherit from the object class. In addition, this information is obtained dynamically when the program is running, and it is not necessary to know the definition of the MyClass class in advance.

Another form of the GetMethods () method

This form allows you to develop a variety of tags to filter the methods you want to get. His general form is: MethodInfo [] GetMethods (BindingFlags bindingAttr)

BindingFlags is an enumeration with enumerated values (many list only 5):

1.DeclareOnly: get only the methods defined by the specified class, not the inherited methods

2.Instance: get instance method

3.NonPublic: get non-public methods

4.Public: get the common method

5.Static: get static methods

GetMethods (BindingFlags bindingAttr) this method, parameters can use or to concatenate two or more tags together, in fact at least Instance (or Static) and Public (or NonPublic) tags. Otherwise, no methods will be obtained.

The copy code is as follows:

View Code

Class MyClass

{

Int x

Int y

Public MyClass (int I, int j)

{

X = I

Y = j

}

Private int sum ()

{

Return x + y

}

Public bool IsBetween (int I)

{

If (x < I & & I < y) return true

Else return false

}

Public void Set (int a, int b)

{

X = a

Y = b

}

Public void Set (double a, double b)

{

X = (int) a

Y = (int) b

}

Public void Show ()

{

Console.WriteLine ("x: {0}, y: {1}", xQuery)

}

}

Class ReflectDemo

{

Static void Main (string [] args)

{

Type t=typeof (MyClass); / / get the Type object that describes the MyClass type

Console.WriteLine ("Analyzing methods in" + t.Name); / / t.name = "MyClass"

MethodInfo [] mi = t.GetMethods (BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); / / No inheritance method is obtained. It is an instance method and is public.

Foreach (MethodInfo m in mi) / / traverses an array of mi objects

{

Console.Write (m.ReturnType.Name); / / returns the return type of the method

Console.Write ("" + m.Name + "("); / / returns the name of the method

ParameterInfo [] pi = m.GetParameters (); / / get the method parameter list and save it in the ParameterInfo object array

For (int I = 0; I < pi.Length; iTunes +)

{

Console.Write (Pi [I] .ParameterType.Name); / / the parameter type name of the method

Console.Write ("" + Pi [I] .Name); / / the parameter name of the method

If (I + 1 < pi.Length)

{

Console.Write (,)

}

}

Console.Write (")")

Console.WriteLine (); / / Line feeds

}

Console.ReadKey ()

}

}

In the above example, you can see that only the common methods defined by the Myclass class display are shown. Private int sum () is not displayed either.

Call a method using reflection

Above we have obtained all the information in the class through reflection, and then we will use reflection to call the methods obtained through reflection.

To call the method obtained by reflection, you need to call the Invoke () method on the MethodInfo instance. The use of Invoke () is demonstrated in the following example.

The following example is: first get the method to be called through reflection, and then use the Invoke () method to call the specified method obtained

The copy code is as follows:

View Code

Class MyClass

{

Int x

Int y

Public MyClass (int I, int j)

{

X = I

Y = j

}

Private int sum ()

{

Return x + y

}

Public bool IsBetween (int I)

{

If (x < I & & I < y) return true

Else return false

}

Public void Set (int a, int b)

{

Console.Write ("Inside set (int,int).")

X = a

Y = b

Show ()

}

Public void Set (double a, double b)

{

Console.Write ("Inside set (double,double).")

X = (int) a

Y = (int) b

Show ()

}

Public void Show ()

{

Console.WriteLine ("x: {0}, y: {1}", x, y)

}

}

Class InvokeMethDemo

{

Static void Main ()

{

Type t=typeof (MyClass)

MyClass reflectOb = new MyClass (10,20)

ReflectOb.Show (); / / output is: XRV 10, YRV 20

MethodInfo [] mi = t.GetMethods ()

Foreach (MethodInfo m in mi)

{

ParameterInfo [] pi = m.GetParameters ()

If (m.Name.Equals ("Set", StringComparison.Ordinal) & & pi [0] .ParameterType = = typeof (int))

{

Object [] args = new object [2]

Args [0] = 9

Args [1] = 10

/ / the parameter reflectOb, which is an object reference, will call the method on the object it points to. If it is a static method, this parameter must be set to null.

/ / Parameter args, which is the parameter array of the calling method. If the parameter is not required, it is null.

M.Invoke (reflectOb, args); / / call the Set method of parameter type int in the MyClass class, and the output is Inside set (int,int). XRO 9, YRO 10

}

}

Console.ReadKey ()

}

}

Get the constructor of the Type object

In the previous explanation, because objects of type MyClass are explicitly created, there is no advantage in using reflection technology to call methods in the MyClass class, which is not as convenient and simple as calling in a normal way. However, if the object is created dynamically at run time, the advantages of reflection capabilities are shown. In this case, you first get a list of constructors and then call one of the constructors in the list to create an instance of that type. With this mechanism, objects of any type can be instantiated at run time without having to specify the type in the declaration statement.

The copy code is as follows:

View Code

Class MyClass

{

Int x

Int y

Public MyClass (int I)

{

X = y + I

}

Public MyClass (int I, int j)

{

X = I

Y = j

}

Public int sum ()

{

Return x + y

}

}

Class InvokeConsDemo

{

Static void Main ()

{

Type t = typeof (MyClass)

Int val

ConstructorInfo [] ci = t.GetConstructors (); / / use this method to get the list of constructors

Int x

For (x = 0; x < ci.Length; x +)

{

ParameterInfo [] pi = ci [x] .GetParameters (); / / gets the parameter list of the current constructor

If (pi.Length = = 2) break; / / if the current constructor has 2 arguments, jump out of the loop

}

If (x = = ci.Length)

{

Return

}

Object [] consargs = new object [2]

Consargs [0] = 10

Consargs [1] = 20

Object reflectOb = ci [x] .invoke (consargs); / / instantiate a type object with two parameters for this constructor, or null if the argument is empty

/ / after instantiation, call the method in MyClass

MethodInfo [] mi = t.GetMethods (BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)

Foreach (MethodInfo m in mi)

{

If (m.Name.Equals ("sum", StringComparison.Ordinal))

{

Val = (int) m.Invoke (reflectOb, null); / / because the type object is instantiated with a constructor of two parameters, the structure returned here is 30

Console.WriteLine ("sum is" + val); / / output sum is 30

}

}

Console.ReadKey ()

}

}

Get a type from an assembly

In the previous exposition, we can see that all the information of a type can be obtained by reflection, but we do not get the MyClass type itself. Although the previous examples can dynamically determine the information of the MyClass class, they are all based on the fact that you know the type name in advance and use it in the typeof statement to get the Type object. Although this approach may work well in many cases, to take full advantage of reflection, we also need to analyze the contents of the assembly to dynamically determine the available types of the program.

With Reflection API, you can load assemblies, get information about it, and create instances of its publicly available types. Through this mechanism, programs can search their environment and take advantage of potential capabilities without having to explicitly define them during compilation. This is a very effective and exciting concept.

To show how to get the types in the assembly, I created two files. The first file defines a set of classes, and the second file reflects the information of each class. The code works as follows.

1. The following code is to compile and generate the MyClass.exe file

The copy code is as follows:

View Code

Class MyClass

{

Int x

Int y

Public MyClass (int I)

{

X = y + I

}

Public MyClass (int I, int j)

{

X = I

Y = j

}

Public int sum ()

{

Return x + y

}

}

Class Demo

{

Static void Main ()

{

Console.WriteLine ("hello word!")

Console.ReadKey ()

}

}

two。 The following code gets the assembly generated above

The copy code is as follows:

View Code

Class Class3

{

Static void Main () {

Assembly asm = Assembly.LoadFrom (@ "C:\ Users\ lenovo\ Documents\ visual studio 2010\ Projects\ Reflection_test\ ConsoleApplication1\ bin\ Debug\ MyClass.exe"); / / load the specified assembly

Type [] alltype = asm.GetTypes (); / / get a list of all types in the assembly

Foreach (Type temp in alltype)

{

Console.WriteLine (temp.Name); / / print out all type names in the MyClass assembly MyClass, Demo

}

Console.ReadKey ()

}

}

The above gets the type in the assembly, and if you want to manipulate the method in the type in the assembly, it looks the same as the method we repeated earlier.

The above is all the content of the article "sample Analysis of reflection in .net". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report