gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:42:56 25 4
gpt4 key购买 nike

为什么整数数组不是对象数组?为什么不能将“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com