我正在尝试运行面板中的所有控件,并查找用户为每个控件更改了哪些属性。
所以我有个密码:
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现在我面临三个问题:
发布于 2012-10-23 12:54:01
Not set to an instance of an object,做些像.
If val IsNot Nothing AndAlso defVal IsNot Nothing AndAlso Not val.Equals(defVal) Then只有在两个值都不是Nothing (又名Null)的情况下,才会进行比较。
不幸的是,#2是一个基本的问题--默认情况下,.Equals检查两个对象引用是否指向内存中的同一个对象--(如果是这样的话)。
Dim A As New SomeClass
Dim B As New SomeClass
If A.Equals(B) Then
...
End If将返回False,除非SomeClass有一个重写的相等比较器,而许多类不这样做。
您可以检查所讨论的值是否是可以比较的类型(Integer、String、Double等)。如果没有,您可以迭代它的属性并再次执行相同的检查。这将允许您比较任何类型的公共属性是否相等,但不能保证类的内部状态相同。
类似于(未经测试的/伪的)..。
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这仍然不理想,因为值的内部状态可能不同。
https://stackoverflow.com/questions/13030461
复制相似问题