C# 中的 Type.Equals() 方法

csharpprogrammingserver side programming更新于 2025/9/25 9:52:17

C# 中的 Type.Equals() 方法用于判断当前 Type 的底层系统类型是否与指定 Object 或 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

相关文章