簡體   English   中英

C#中的自定義等於方法

[英]Custom Equals Method in C#

我編寫了一個名為baseCommodity的類,它包含一個自定義的Equals方法:

public override bool Equals(object obj)
{
    BaseCommodity other = obj as BaseCommodity;
    return other != null && other.GetType() is this.GetType());
}

我想將other.GetType()this的類型進行比較,但是is this.GetType()無法正常工作。 我不斷收到錯誤消息“ this', expecting符號為意外符號this', expecting類型為”。

您想要==代替:

return other != null && other.GetType() == this.GetType();

當您知道可以檢查的對象的編譯時類型標記時,可以使用is

附帶說明一下,如果要覆蓋Equals(object other) ,也許您還想實現IEquatable<BaseCommodity>並覆蓋它的Equals(BaseCommodity other) ,這樣可以節省類型檢查。

另外,這是一個非常弱的類型相等性檢查。

也許更多的信息將是一個很好的答案。

GetType返回類型對象 ,而不是類型標記 類型標記使用is進行處理,類型對象使用相等(==)進行比較。

換一種說法:

object a = 12893;
if (a is int) // compare by token:
{ ... }

object a = 12345;
if (a.GetType() == typeof(int)) // compare by equality of type object.
{ ... }

PS:平等會給繼承帶來奇怪的結果。 在這種情況下,您可能要改用SomeType.IsAssignableFrom

正如其他人所述,這里需要比較運算符==

is是類型檢查,它與左側的變量和右側的類型一起使用:

string s = "";
bool isString = s is string;

請注意, GetType的結果不是類型 ,它是代表類型變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM