考虑这个类,它重载了 Person 类的 = 运算符。这适用于 VB.NET:
Public Class Person
Public Sub New(ByVal FirstName As String, ByVal LastName As String)
_FirstName = FirstName
_LastName = LastName
End Sub
Private _LastName As String
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
Private _FirstName As String
Public Property FirstName() As String
Get
Return _FirstName
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
Public Shared Operator <>(ByVal Person1 As Person, ByVal Person2 As Person) As Boolean
Return Not (Person1 = Person2)
End Operator
Public Shared Operator =(ByVal Person1 As Person, ByVal Person2 As Person) As Boolean
Return Person1.FirstName = Person2.FirstName AndAlso Person1.LastName = Person2.LastName
End Operator
Public Class Test
Public Sub TestIt()
Dim P1 As New Person("f1", "l1")
Dim P2 As Person = Nothing
Dim IsEqual As Boolean = False
If P1 IsNot Nothing AndAlso P2 IsNot Nothing Then
If P1 = P2 Then
IsEqual = True
End If
End If
End Sub
End Class
End Class
和 C# 中的同一个类:
public Person(string FirstName, string LastName)
{
_FirstName = FirstName;
_LastName = LastName;
}
private string _LastName;
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
private string _FirstName;
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public static bool operator !=(Person Person1, Person Person2)
{
return !(Person1 == Person2);
}
public static bool operator ==(Person Person1, Person Person2)
{
return Person1.FirstName == Person2.FirstName && Person1.LastName == Person2.LastName;
}
public class Test
{
public void TestIt()
{
Person P1 = new Person("f1", "l1");
Person P2 = null;
bool IsEqual = false;
if (P1 != null && P2 != null)
{
if (P1 == P2)
{
IsEqual = true;
}
}
}
}
使用 C# 类,如果在Person
测试中使用null
该==
函数是否为null
. 也就是说,是否有与测试Is Nothing
分开的与VB 等效的对应功能==
?似乎 C#==
两者都使用。
我试过了object.IsEqual
;那看起来也错了。