C# 中的 Type.Equals() 方法


C# 中的 Type.Equals() 方法確定當前 Type 的底層系統型別是否與指定的物件或型別的底層系統型別相同。

語法

public virtual bool Equals (Type o);
public override bool Equals (object o);

以上,引數是其底層系統型別要與當前 Type 的底層系統型別進行比較的物件。

我們現在來看一個示例,實現 Type.Equals() 方法 −

using System;
public class Demo {
   public static void Main(string[] args) {
      Type val1 = typeof(System.UInt16);
      Type val2 = typeof(System.Int32);
      Console.WriteLine("Are both the types equal? "+val1.Equals(val2));
   }
}

輸出

這將產生以下輸出 −

Are both the types equal? False

現在我們來看另一個示例,實現 Type.Equals() 方法 −

示例

using System;
using System.Reflection;
public class Demo {
   public static void Main(string[] args) {
      Type type = typeof(String);
      Object obj = typeof(String).GetTypeInfo();
      Type type2 = obj as Type;
      if (type2 != null)
         Console.WriteLine("Both types are equal? " +type.Equals(type2));
      else
         Console.WriteLine("Cannot cast!");
   }
}

輸出

這將產生以下輸出 −

Both types are equal? True

更新於:2019 年 11 月 4 日

776 瀏覽次數

開啟您的 職業生涯

透過完成課程獲得認證

開始吧
廣告