首页 > 解决方案 > 为什么这些不一样?为什么 `type.GetType() is Test` 在 C# 中不是真的?

问题描述

public class Test { }
public class InheritTest : Test { }

private void Main(string[] args)
{
   var test        = new Test();
   var inheritTest = new InheritTest();

   Console.WriteLine($"{test.GetType() is Test}");               // False
   Console.WriteLine($"{inheritTest.GetType() is InheritTest}"); // False
}

GetType是实际实例。但为什么不是type.GetType() is Test真的?

标签: c#

解决方案


是(C# 参考)

is 关键字在运行时评估类型兼容性。它确定对象实例或表达式的结果是否可以转换为指定的类型。

Object.GetType 方法 ()

获取当前实例的类型。

基本上不需要GetType()

更新

type.GetType()返回一个System.Type

因此,按照您的初衷,您可以想象以下内容

// as you see, GetType() returns a type
Console.WriteLine($"{type.GetType() is Type}"); // True

typeof也返回 a Type,因此也可以使用以下内容进行比较

用于获取某个类型的 System.Type 对象

Console.WriteLine($"{type.GetType() == typeof(Test)}"); // True

推荐阅读