【问题标题】:How to get property.value from reflection.assembly?如何从reflection.assembly中获取property.value?
【发布时间】:2012-12-08 01:57:39
【问题描述】:

如何从reflection.assembly中获取property.value?

Dim assembly As Assembly = assembly.GetExecutingAssembly()

For Each assemblyType As Type In assembly.GetTypes()
        If assemblyType.IsSubclassOf(GetType(Form)) Then
            'Dim name As AssemblyName() = assembly.GetReferencedAssemblies()


            If assemblyType.BaseType.ToString.EndsWith("Form2") Then
                Dim props As PropertyInfo = _
                GetType(Form2).GetProperty("FriendlyName")


                If Not props Is Nothing Then
                    ComboBox1.Items.Add(assemblyType.Namespace )

                End If
'//Here I want to get Prop.value that is string type



End If

【问题讨论】:

    标签: vb.net reflection


    【解决方案1】:

    要通过反射获取属性的值,请调用PropertyInfo.GetValue

    但是,假设这是一个实例属性,您将需要一个类型的实例来获取属性值。例如,如果 FriendlyName 是 Form2 类的实例属性,则您需要指定要为其获取 FriendlyName 的 Form2 实例。 (您将把它作为 obj 参数传递给 PropertyInfo.GetValue;在这种情况下,您可以为 index 参数传递 null。)

    【讨论】:

      【解决方案2】:

      以伊托尔森所写的内容为基础:

      来自 MCTS:.net 2.0:应用程序开发基础

      首先获取程序集:

      Dim path As String = "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\" + _ "mscorlib.dll"

      将Assembly 调暗为Assembly = Assembly.LoadFile(path) Dim hashType 作为类型 = theAssembly.GetType("System.Collections.Hashtable")

      一旦你有了类型,你就可以要求它提供一个 ConstructorInfo 对象来用于构造 你的新类型:

      Dim argumentTypes() As Type = Type.EmptyTypes ' 空构造函数 调光器作为 ConstructorInfo = hashType.GetConstructor(argumentTypes)

      在 ConstructorInfo 对象中表示的方法是一个专门的 MethodBase 对象 它看起来和行为都像一个典型的方法,但总是返回一个特定的实例 类型。在此示例中,您要求 Type 类返回一个空的构造函数。 (您提供了一个空的类型数组来指定空的构造函数。)您 也可以通过提供一个数组来请求具有特定参数的构造函数 构造函数参数类型,如下所示:

      Dim argumentTypes() As Type = _ New Type() {GetType(System.Int32)} ' 一 Int32 Dim ctor As 类型的参数 构造函数信息 = hashType.GetConstructor(argumentTypes)

      一旦你有了 ConstructorInfo 对象,创建一个对象就像调用一样简单 构造函数。以下是如何调用空构造函数:

      将 newHash 调暗为对象 = ctor.Invoke(New Object() {})

      一旦你有了一个对象的实例,你只需使用反射来获取信息类 你需要调用,然后调用 info 类来执行代码。

      例如,在新的 Hashtable 实例上调用 Add 方法:

      Dim meth As MethodInfo = hashType.GetMethod("Add")

      meth.Invoke(newHash, New Object() {“嗨”、“你好”})

      您现在可以使用 PropertyInfo 类来获取您的项目中的项目数 Hashtable 以验证 Add 是否按预期工作:

      Dim prop As PropertyInfo = hashType.GetProperty("Count")

      Dim count As Integer = CType(prop.GetValue(newHash, 无),整数)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-13
        • 2018-09-12
        • 2020-05-22
        • 2014-07-06
        • 2011-06-13
        • 2012-08-09
        • 2014-08-22
        相关资源
        最近更新 更多