gpt4 book ai didi

c# - 什么是包装转换?

转载 作者:可可西里 更新时间:2023-11-01 09:01:46 26 4
gpt4 key购买 nike

当您尝试将值从一种类型转换为另一种不兼容的类型时,您会在 C# 中收到以下错误:

CS0039 Cannot convert type A to B via reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

我知道如何解决这个问题,但我的问题是关于转化类型本身。它提到了引用(父类(super class)到子类,反之亦然)、装箱和拆箱(值类型到对象)和空类型(例如 int 到 int?)转换,但什么是包装转换?这对我来说并不明显,搜索该术语只会返回有关错误 CS0039 的结果,而不是对该概念的解释。

最佳答案

包装将不可为 null 的值类型转换为其等效的可为 null 的值类型。展开是相反的。例如:

int x = 5;
int? y = x; // Wrapping
int z = (int) y; // Unwrapping

C# 规范实际上并未将这些称为“包装转换”和“展开转换”,但它确实讨论了包装和展开。来自 C# 5 规范的第 4.1.10 节,或 online spec (强调我的):

An instance for which HasValue is false is said to be null. A null instance has an undefined value. Attempting to read the Value of a null instance causes a System.InvalidOperationException to be thrown. The process of accessing the Value property of a nullable instance is referred to as unwrapping. In addition to the default constructor, every nullable type T? has a public constructor that takes a single argument of type T. Given a value x of type T, a constructor invocation of the form

new T?(x)

creates a non-null instance of T? for which the Value property is x. The process of creating a non-null instance of a nullable type for a given value is referred to as wrapping.

关于c# - 什么是包装转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49013273/

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