c# - 为什么 "new int[n] is object[]"是假的?为什么 "int[] is object[] arr"是模式错误?

标签 c#

为什么整数数组不是对象数组?为什么不能将“object[]”类型的模式用于“int[]”?

    1 is object
    True
    new int[10] is object
    True
    new int[10] is object[]         // Why?
    False
    (Array)new int[10] is object[]
    False
    (Array)new object[10] is object[]
    True
    new object() is object
    True
    new object[10] is object
    True
    new object[10] is object[]
    True

    int[] arr = new int[10];
    // Why the compilation error?
    // error CS8121: An expression of type 'int[]' cannot be handled by a pattern of type 'object[]'
    if (arr is object[] objArr)   
        Console.WriteLine(objArr);
    // And this works:        
    if ((Array)arr is object[] objArr)
        Console.WriteLine(objArr);

我在源代码中遇到了这一行:https://source.dot.net/#System.Private.CoreLib/Array.cs,1644

.NET 版本为 3.1.10(与单声道 6.4.0 相同)。

最佳答案

实际上(如果我理解正确的话),在这种情况下,这是因为值类型不是协变的:

(Array)new string[10] is object[] 
true

(Array)new int[10] is object[]
false

CLR 不允许它,因为它需要保留身份,而装箱不会,它从根本上改变了内存中的类型

Eric LippertRepresentation and identity 上有一篇关于身份的很棒的博客文章:

covariant and contravariant conversions of interface and delegate types require that all varying type arguments be of reference types. To ensure that a variant reference conversion is always identity-preserving, all of the conversions involving type arguments must also be identity-preserving. The easiest way to ensure that all the non-trivial conversions on type arguments are identity-preserving is to restrict them to be reference conversions.

关于c# - 为什么 "new int[n] is object[]"是假的?为什么 "int[] is object[] arr"是模式错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60334166/

相关文章:

c# - 如何在 ASP.NET Core 身份验证中将 OAuth 回调配置到不同的域

c# - 设置文件中的光标位置

c# - Xamarin Studio 中 iOS 应用程序的屏幕布局乱序

c# - 如何使用身份在 MVC 5 中自定义用户表?

c# - 如何验证闰年的 DateTime

c# - 从二进制形式转换 float NaN 值,反之亦然会导致不匹配

c# - 在 C# 中使用 DateTime 的月份

c# - NHibernate:一个基类,几个映射

c# - ".RestoreDirectory"不工作

c# - 将 C# Count() 与函数一起使用