首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GetType.GetProperties

GetType.GetProperties
EN

Stack Overflow用户
提问于 2012-10-23 12:30:42
回答 1查看 3.1K关注 0票数 1

我正在尝试运行面板中的所有控件,并查找用户为每个控件更改了哪些属性。

所以我有个密码:

代码语言:javascript
复制
    Private Sub WriteProperties(ByVal cntrl As Control)

    Try
        Dim oType As Type = cntrl.GetType

        'Create a new control the same type as cntrl to use it as the default control                      
        Dim newCnt As New Control
        newCnt = Activator.CreateInstance(oType)

        For Each prop As PropertyInfo In newCnt.GetType().GetProperties
            Dim val = cntrl.GetType().GetProperty(prop.Name).GetValue(cntrl, Nothing)
            Dim defVal = newCnt.GetType().GetProperty(prop.Name).GetValue(newCnt, Nothing)

            If val.Equals(defVal) = False Then
               'So if something is different....
            End If

        Next
    Catch ex As Exception
        MsgBox("WriteProperties : " &  ex.Message)
    End Try
End Sub

现在我面临三个问题:

  1. 当属性引用图像(BackGround图像)时,我有一个错误: ImageObject引用没有设置为对象的实例。
  2. 第二个问题是,代码: 如果val.Equals(defVal) = False,那么如果有什么不同.结束于 有时,当val和defVal相同时执行。这种情况发生在属性是"parentProperty“的情况下,比如FlatAppearance (它具有更多的子属性)。
  3. 我的循环不查看我想要的基本属性,比如大小或位置
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-23 12:54:01

Not set to an instance of an object,做些像.

代码语言:javascript
复制
If val IsNot Nothing AndAlso defVal IsNot Nothing AndAlso Not val.Equals(defVal) Then

只有在两个值都不是Nothing (又名Null)的情况下,才会进行比较。

不幸的是,#2是一个基本的问题--默认情况下,.Equals检查两个对象引用是否指向内存中的同一个对象--(如果是这样的话)。

代码语言:javascript
复制
Dim A As New SomeClass
Dim B As New SomeClass

If A.Equals(B) Then
    ...
End If

将返回False,除非SomeClass有一个重写的相等比较器,而许多类不这样做。

您可以检查所讨论的值是否是可以比较的类型(Integer、String、Double等)。如果没有,您可以迭代它的属性并再次执行相同的检查。这将允许您比较任何类型的公共属性是否相等,但不能保证类的内部状态相同。

类似于(未经测试的/伪的)..。

代码语言:javascript
复制
Function Compare (PropA, PropB) As Boolean
    Dim Match = True
    If PropA.Value Is Nothing Or PropB.Value Is Nothing
       Match = False
    Else
       If PropA.Value.GetType.IsAssignableFrom(GetType(String)) Or
          PropA.Value.GetType.IsAssignableFrom(GetType(Integer)) Or ... Then
           Match = PropB.Value.Equals(PropB.Value)
       Else
           For Each Prop In PropA.Value.GetType.GetProperties()
               Match =  Compare(Prop, PropB.Value.GetType.GetProperty(Prop.Name))
               If Not Match Then Exit For
           Next
        End If    
    End If    
    Return Match
End Function

这仍然不理想,因为值的内部状态可能不同。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13030461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档