日期:2013-01-01  浏览次数:20512 次

浅谈VB.NET文章系列之一通过例子,浅谈反射(Reflection)的应用说明:应该说这篇短文根本算不上什么深入的分析性的文章,所以在标题前加上了“浅谈”二字,希望对于一般的读者来说,可以给你一个相对直观些的对反射的认识。                                                             --2005/05/23 于东莞在这里对反射以及反射的概念在最后给出简要的解释。一.用来测试的程序集文件的建立。

首先你需要建立一个类库文件(编译后扩展名为.dll),名字假设为:reflection_newtest

系统会默认地新建一个类文件class1,把它该成我们用来测试的类person

具体代码如下:(类的代码比较简单,这里不做解释,如有不明之处,请查看类的相关文档.)

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

  

二.测试验证的程序

建立一个winform的程序,命名假设为:testreflection

从工具栏里拖两个按钮,命名为button1,button2.

1.在程序的最上面加入引用:

Imports System

Imports System.Reflection

Imports System.Type

2.在button1的click事件里写:

  

  

        Dim asm As [Assembly] ‘由于assembly是关键字,所以要加[]

        asm = Reflection.Assembly.LoadFrom("G:\练习\reflection_newtest\bin\reflection_newtest.dll") ‘这里假设上面的reflection_newtest文件的位置在G:\练习 的文件夹。