c# - 为什么这些不一样?为什么 `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
真的?
解决方案
is 关键字在运行时评估类型兼容性。它确定对象实例或表达式的结果是否可以转换为指定的类型。
获取当前实例的类型。
基本上不需要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
推荐阅读
- c# - 使用 c# 反序列化复杂的 Json
- haskell - 无法添加经典前奏依赖项
- mysql - 如何使用 bash 脚本在条目内使用逗号格式化 csv?
- c# - 如何在 C# .net Core 跨平台中获取 USB 设备的详细信息
- python - 尝试在数据块上运行气流但出现错误
- python - Sagemaker 不使用 GPU,即使它部署在 GPU 实例中
- python - 在正则表达式中使用 sub() 方法时如何避免突变?
- amazon-web-services - 使用计划中的配额有什么限制?
- bash - 我需要一个 shell 脚本来移动服务器生成的日志
- nginx - nginx将规则重写为IIS7规则?