【问题标题】:Get value of a property with propertyinfo object使用 propertyinfo 对象获取属性的值
【发布时间】:2016-12-19 18:41:15
【问题描述】:

有没有办法通过 propertyinfo 对象获取对象属性的值?

伪代码:

propertyinfoObject = Text
myobject.toCommand(propertyinfoObject)

上面的伪代码应该和上面的一样

myobject.Text

我的目标是创建一个适用于任何对象的简单属性表单(稍后我将使用关键字过滤出我希望使用的选项)。

我的真实密码

Public Class PropertiesForm
Dim propertyInfoVar() As PropertyInfo
Dim Properties As New Form2
Dim listItem As New ListViewItem
Dim stringarray() As String
Public Sub New(ByRef sender As Object)



    propertyInfoVar = sender.GetType().GetProperties()
    For Each p In propertyInfoVar
        stringarray = {p.Name.ToString, #INSERT VALUE SOMEHOW HERE#}

        listItem = New ListViewItem(stringarray)
        Properties.ListView1.Items.Add(listItem)
    Next
    Properties.Visible = True
End Sub

编辑 只需按照下面的建议使用 propertyGrid!

【问题讨论】:

  • 不是没有,但 PropertyGrid 不是已经做了所有这些了吗?
  • :) 你说的太对了!我不知道它存在。 .net 框架是如此之大,以至于当你是新手时很容易错过一些关键的东西:)。也许我应该从头到尾阅读我的 VB 书,而不仅仅是在里面跳来跳去!

标签: vb.net properties propertyinfo


【解决方案1】:

标准PropertyGrid 已经为您完成了所有这些工作。过滤属性不是那么明显,方法如下:

该控件包含一个BrowsableAttributes 属性,它允许您指定只显示具有指定属性值的属性。您可以使用现有属性或自定义属性。这专门用于标记可见道具:

<AttributeUsage(AttributeTargets.Property)>
Public Class PropertyGridBrowsableAttribute
    Inherits Attribute

    Public Property Browsable As Boolean

    Public Sub New(b As Boolean)
        Browsable = b
    End Sub
End Class

将其应用于 Employee 类以隐藏工资率或其他任何内容:

Public Class Employee
    <PropertyGridBrowsable(True)>
    Public Property FirstName As String
    ...
    <PropertyGridBrowsable(False)>
    Public Property PayRate As Decimal
    <PropertyGridBrowsable(False)>
    Public Property NationalInsuranceNumber As String

测试代码:

Dim emp As New Employee With {.Dept = EmpDept.Manager,
                                    .FirstName = "Ziggy",
                                    .PayRate = 568.98D,
                                     ...
                                    .NationalInsuranceNumber = "1234567"
                                   }

propGrid.BrowsableAttributes = New AttributeCollection(New PropertyGridBrowsableAttribute(True))

propGrid.SelectedObject = emp

BrowsableAttributes是一个集合,所以你可以添加几个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2023-03-13
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多