c# - == 运算符如何与 System.Type 一起使用

标签 c#

typeof(int) == typeof(int)

这个表达式如何求值??

当我使用

Console.WriteLine(typeof(int));

它使用对象的ToString() 方法输出System.Int32。所以我假设在这个表达式中

 typeof(int) == typeof(int)

ToString() 将两者都转换为 System.Int32,然后比较它们的字符串。是真的吗??

或者其他事情发生

最佳答案

没有。像其他所有类通常所做的那样,它使用相等比较器 (==) System.Type 已被覆盖,并且 Equals 方法在两者之一上实例来检查它们是否相等。

typeof(int) 返回一个 Type,因此 Type.Equals 被调用。可以看源here .

你会看到它最终使用这个来比较两个实例:

return (Object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType));

关于c# - == 运算符如何与 System.Type 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26211681/

相关文章:

C# - 使用内联 SQL 恢复 SQL Server 数据库

c# - 列表框项的背景颜色(Windows 窗体)

c# - 在上传到 S3 的对象上设置 `Content-Disposition`?

c# - .Net5 身份注销

C# 性能最佳实践 : object creation vs reuse

c# - 如何更新为二维数组?

c# - 无法使此 Func<T,T> 工作

c# - "Intelligent"将 double 转换为两个不同格式的字符串?

c# - 如果使用的库不支持异步等待,在哪里使用 Task.Run

c# - XmlSerializer 为 x86 和 x64 生成不同的输出