About VB. one of the NET article series illustrates the application of Reflection Through examples: it should be said that this short article is not an in-depth analysis article, therefore, I added the word "talking" before the title, hoping that the average reader can give you a relatively intuitive understanding of reflection. -- At the end of /05/23, Dongguan briefly explained the concepts of reflection and reflection. 1. Create an assembly file for testing.
First, you need to create a class library file (with the. dll extension after compilation). The name is assumed to be reflection_newtest.
The system will create a new class file class1 by default and convert it to the class person we use for testing.
The Code is as follows: (the class code is relatively simple and will not be explained here. For details, see the Class documentation .)
Public Class person
Public firstname As String
Public lastname As String
Dim m_age As Short
Dim m_emailaddress (4) As String
Public Sub New ()
MyBase. new ()
End Sub
Public Sub New (ByVal firstname As String, ByVal lastname As String)
Me. firstname = firstname
Me. lastname = lastname
End Sub
Public Property age () As Short
Get
Return m_age
End Get
Set (ByVal Value As Short)
M_age = Value
End Set
End Property
Public Property emailaddress (ByVal index As Short) As String
Get
Return m_emailaddress (index)
End Get
Set (ByVal Value As String)
M_emailaddress (index) = Value
End Set
End Property
Sub sendemail (ByVal msg As String, Optional ByVal priorty As Integer = 1)
Console. WriteLine ("message to" & firstname & "& lastname)
Console. WriteLine ("priority" & priorty. ToString)
Console. WriteLine (msg)
End Sub
End Class
2. Procedures for testing and verification
Create a winform program named as testreflection.
Drag two buttons from the toolbar and name them button1 and button2.
1. Add reference at the top of the program:
Imports System
Imports System. Reflection
Imports System. Type
2. In the click event of button1, write:
Dim asm As [Assembly] 'Because assembly is a keyword, you need to add []
Asm = Reflection. Assembly. LoadFrom ("G: \ exercise \ reflection_newtest \ bin \ reflection_newtest.dll") 'assume that the above reflection_newtest file is located in the G: \ exercise folder.
Console. WriteLine (asm. FullName) 'output fully qualified name
Console. WriteLine (asm. Location) 'gets the Location of the file's basic code format
Console. WriteLine (asm. CodeBase) 'gets the Location of the initially specified assembly, which is generally similar to the Location method
Dim mo As [Module] 'traversal Module
For Each mo In asm. GetModules
Console. WriteLine (mo. FullyQualifiedName)
Next
Dim ty As Type
For Each ty In asm. GetTypes 'traverses all types of information
Console. WriteLine (ty. FullName)
Next
'Load an instance dynamically
Dim o As Object = asm. CreateInstance ("reflection_newtest.person ")
Console. WriteLine ("********************")
Console. WriteLine (o. GetType. FullName)
Note: The usage here is relatively simple. Please continue to read it!
3. Establish the test process
'Retrieve the traversal type. The system class library file mscorlib. dll is used here.
Private Sub testtypeenumeration ()
Dim asm As [Assembly] = Reflection. Assembly. Load ("mscorlib ")
Dim t As Type
For Each t In asm. GetExportedTypes 'test the current file
If t. IsClass then' is a class
Console. WriteLine (t. Name & "(class )")
ElseIf t. IsEnum then'
Console. WriteLine (t. Name & "(enum )")
ElseIf t. IsValueType then' if it is a value type
Console. WriteLine (t. Name & "(structure )")
ElseIf t. IsInterface then'
Console. WriteLine (Name & "(interface )")
Else 'others
'Not processed
End If
Next
End Sub
'Get all the information of a certain type (string is used as an example here)
'From the above load and type. gettype, they are all ways to create an assembly.
Private Sub testatypememberinfo1 ()
Dim stringtype As Type = Type. GetType ("System. String") 'to obtain the System type of the specified name. You can also use Type. gettype (string)
Dim minfos () As MemberInfo 'type array
Dim mi As MemberInfo
Minfos = stringtype. GetMembers
For Each mi In minfos
Console. WriteLine (mi. Name)
Next
'Get Public Non-shared and inherited members
Minfos = stringtype. GetMembers (BindingFlags. Public Or BindingFlags. Instance Or BindingFlags. DeclaredOnly)
'The interval is set to make it easier to see the output.
Console. WriteLine ("*********************")
For Each mi In minfos
Console. WriteLine (mi. Name)
Next
'Same Interval Settings
Console. WriteLine ("*********************")
'Get all methods
For Each mi In stringtype. GetMethods
Console. WriteLine (mi. Name)
Next
End Sub
'Use a specific method to display a specific type
Private Sub testatypememberinfo ()
Dim stringtype As Type = Type. GetType ("System. String") 'gets the System Type of the specified name
'Traversal of specific types of attributes
Dim pinfos () As PropertyInfo = stringtype. GetProperties
Dim mi As MemberInfo
For Each mi In pinfos
Console. WriteLine (mi. Name)
Next
End Sub
'Use the findmember method to traverse type 1
Private Sub testfindmember1 ()
Dim stringtype As Type = Type. GetType ("System. String ")
'For the findmembers method, its parameters are respectively the type to be obtained (available or combination), filtering conditions (available or combination ),
The parameter passed to the delegate function.
Dim minfos () As MemberInfo = stringtype. FindMembers (MemberTypes. Method _
Or MemberTypes. Property, BindingFlags. Instance Or BindingFlags. Public ,_
AddressOf filterbyname1, "C ")
Dim mi As MemberInfo
For Each mi In minfos
Console. WriteLine (mi. Name)
Next
End Sub
'Delegate function 1: filter the methods and attributes of Public instances whose names start with C (this function returns true, meaning it meets the requirements)
Private Function filterbyname1 (ByVal m As MemberInfo, ByVal filtercriteria As Object) As Boolean
'If the member name starts with the filter function's 2nd parameters, true is returned.
If m. Name. StartsWith (filtercriteria. ToString) Then
Return True
End If
End Function
'Use the findmember method to traverse type 2
Private Sub testfindmember2 ()
Dim returntype As Type = Type. GetType ("System. Int32 ")
Dim minfos () As MemberInfo = returntype. FindMembers (MemberTypes. Method Or MemberTypes. Property ,_
BindingFlags. Instance Or BindingFlags. Public, AddressOf filterbyname2, returntype)
Dim mi As MemberInfo
For Each mi In minfos
Console. WriteLine (mi. Name)
Next
End Sub
'Delegate function 2
Private Function filterbyname2 (ByVal m As MemberInfo, ByVal filtercriteria As Object) As Boolean
If m. MemberType = MemberTypes. Property Then
Dim pi As PropertyInfo = CType (m, PropertyInfo)
Return (pi. PropertyType Is filtercriteria) 'returns true if the type of this attribute Is the same as that of the 2nd Parameter
ElseIf m. MemberType = MemberTypes. Method Then
Dim mi As MethodInfo = CType (m, MethodInfo)
Return (mi. ReturnType Is filtercriteria) 'returns true if the Return type of this method Is the same as that of the 2nd Parameter
End If
End Function
'Call of overload Functions
Private Sub testoverloadmemberinfo ()
Dim stringtype As Type = Type. GetType ("System. String ")
'A type array
Dim argtypes () As Type = {Type. GetType ("System. String"), Type. GetType ("System. String ")}
Dim mi As MemberInfo = stringtype. GetMethod ("Compare", argtypes)
Console. WriteLine (mi. Name)
End Sub
'Enumeration parameter type
Private Sub testcallingsyntax ()
Dim stringtype As Type = Type. GetType ("System. String ")
Dim mi As MethodInfo = stringtype. GetMethod ("Copy ")
Dim pinfos () As ParameterInfo = mi. GetParameters
Dim I As Integer
'Lists the types of parameters and uses/to connect them.
For I = 0 To pinfos. GetUpperBound (0)
Console. WriteLine (pinfos (I). Name & "/" & pinfos (I). ParameterType. ToString)
Next
End Sub
'Use reflection to create an instance and assign a value to the attribute
Private Sub testreadwriteproperties ()
Try
Dim asm As [Assembly] = Reflection. Assembly. LoadFrom ("G: \ exercise \ reflection_newtest \ bin \ reflection_newtest.dll ")
Dim ty As Type = asm. GetType ("reflection_newtest.person ")
Dim m As Object = Activator. CreateInstance (ty)
Dim pi As PropertyInfo = ty. GetProperty ("age ")
Pi. SetValue (m, 5S, Nothing) 'must specify the type of the value, if the short type, must add s
Console. WriteLine (pi. GetValue (m, Nothing ))
Catch ex As Exception
MessageBox. Show (ex. Message)
End Try
End Sub
'Test string attributes (including parameters)
Private Sub testreadwritepropertytieswithargs ()
Try
Dim asm As [Assembly] = Reflection. Assembly. LoadFrom ("G: \ exercise \ reflection_newtest \ bin \ reflection_newtest.dll ")
Dim ty As Type = asm. GetType ("reflection_newtest.person ")
Dim m As Object = Activator. CreateInstance (ty)
Dim pi As PropertyInfo = ty. GetProperty ("emailaddress ")
Dim params () As Object = {1 S} 'note that the parameter type is strictly matched.
Pi. SetValue (m ," 321 north street ", params) 321 north street", params)
Console. WriteLine (pi. GetValue (m, params ))
Catch ex As Exception
MessageBox. Show (ex. Message)
End Try
End Sub
'Test procedure using the invoke Method
Private Sub testinvokemethod ()
Dim asm As [Assembly] = Reflection. Assembly. LoadFrom ("G: \ exercise \ reflection_newtest \ bin \ reflection_newtest.dll ")
Dim ty As Type = asm. GetType ("reflection_newtest.person ")
Dim m As Object = Activator. CreateInstance (ty)
Dim mi As MethodInfo = ty. GetMethod ("sendemail ")
'Parameter array of the definition process
Dim params (mi. GetParameters. Length-1) As Object
Try
Params (0) = "this is message"
Params (1) = 3
'Triggering Process
Mi. Invoke (m, params)
Catch ex As Exception
MessageBox. Show (ex. Message)
End Try
End Sub
'Test procedure using the invokemember Method
Private Sub testinvokemember ()
Dim asm As [Assembly] = Reflection. Assembly. LoadFrom ("G: \ exercise \ reflection_newtest \ bin \ reflection_newtest.dll ")
Dim ty As Type = asm. GetType ("reflection_newtest.person ")
Dim m As Object = Activator. CreateInstance (ty)
Dim args () As Object = {"francesco "}
Try
'Set the value of the firstname Field
Ty. InvokeMember ("firstname", BindingFlags. SetField, Nothing, m, args)
'Read the value of the firstname field. The last parameter is not used at this time.
Dim value As Object = ty. InvokeMember ("firstname", BindingFlags. GetField, Nothing, m, Nothing)
Console. WriteLine (value. ToString)
Dim args2 () As Object = {35 S} 'note that the type of the array element must strictly match the short type,
'Set the property value. The parameter indicates the property parameter.
Ty. InvokeMember ("age", BindingFlags. SetProperty, Nothing, m, args2)
'Read attribute values
Dim value1 As Object = ty. InvokeMember ("age", BindingFlags. GetProperty, Nothing, m, Nothing)
Console. WriteLine (value1.ToString)
Dim args3 () As Object = {"this is a message", 2}
'Triggering Process
Ty. InvokeMember ("sendemail", BindingFlags. InvokeMethod, Nothing, m, args3)
Catch ex As Exception
MessageBox. Show (ex. Message)
End Try
End Sub
'/////////////////////////////////////// ////////////////////
'Dynamically create an object (use the default constructor)
Private Sub testobjectcreation1 ()
Dim asm As [Assembly] = Reflection. Assembly. LoadFrom ("G: \ exercise \ reflection_newtest \ bin \ reflection_newtest.dll ")
Dim ty As Type = asm. GetType ("reflection_newtest.person ")
Try
Dim m As Object = Activator. CreateInstance (ty)
Console. WriteLine ("A {0} object has been created", m. GetType. Name)
Catch ex As Exception
MessageBox. Show (ex. Message)
End Try
End Sub
'Use methods with parameters (Use constructors with parameters)
Private Sub testobjectcreation2 ()
Dim asm As [Assembly] = Reflection. Assembly. LoadFrom ("G: \ exercise \ reflection_newtest \ bin \ reflection_newtest.dll ")
Dim ty As Type = asm. GetType ("reflection_newtest.person ")
Dim params () As Object = {"Joe", "Doe "}
Try
Dim o As Object = System. Activator. CreateInstance (ty, params)
Console. WriteLine (o. GetType. Name)
Catch ex As Exception
MessageBox. Show (ex. Message)
End Try
End Sub
'The method of calling constructor to create an object (Instance) is relatively cumbersome and troublesome.
Private Sub testobjectcreation3 ()
Dim asm As [Assembly] = Reflection. Assembly. LoadFrom ("G: \ exercise \ reflection_newtest \ bin \ reflection_newtest.dll ")
Dim ty As Type = asm. GetType ("reflection_newtest.person ")
Dim types () As Type = {GetType (System. String), GetType (String )}
Dim ci As ConstructorInfo = ty. GetConstructor (types) 'obtains information about the constructor with two string parameters.
Dim params () As Object = {"Joe", "Doe"} 'Array Used for initialization
Dim o As Object = ci. Invoke (params) 'executes this Constructor
Console. WriteLine (o. GetType. Name)
End Sub
4. Write in the click event of button2: (this operation is to verify all the test processes. In order to identify the results of the process, all others are temporarily commented out. You can remove comments as needed .)
'Testtypeenumeration ()
'Testatypememberinfo1 ()
'Testatypememberinfo2 ()
'Testfindmember1 ()
'Testfindmember2 ()
Testoverloadmemberinfo ()
'Testcallingsyntax ()
'Testreadwriteproperties ()
'Testreadwritepropertytieswithargs ()
'Testinvokemethod ()
'Testinvokemember ()
'Testobjectcreation1 ()
'Testobjectcreation2 ()
'Testobjectcreation3 ()
Note: There are not many explanations here, and the code has complete comments. If you have any omissions or errors, please point out! Thank you!
A brief description of related terms: Reflection (Reflection): Method Assembly for obtaining runtime type information in. Net: compiled. dll and exe files. You can obtain information about running accessories, dynamically load the accessories, find the type information in the accessories, and create instances of this type. Type: The type here is differentiated between the value type and the reference type. It includes classes, enumerations, value types, and interfaces.