什么是换行转换? [英] What is a wrapping conversion?

查看:47
本文介绍了什么是换行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When you try to cast a value from a type to another incompatible type, you get the following error in C#:


CS0039无法通过引用转换,装箱转换,拆箱转换,换行转换或空类型转换将类型A转换为B

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

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

I understand how to potentially fix this, but my question is about the types of conversions themselves. It mentions reference (superclass to subclass or vice versa), boxing and unboxing (value type to object) and null type (e.g. int to int?) conversions, but then what is a wrapping conversion? This one isn't obvious to me, and searching for this term just brings back results about error CS0039, instead of an explanation of the concept.

推荐答案

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

Wrapping converts a non-nullable value type to its nullable equivalent. Unwrapping is the reverse. For example:

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

C#规范实际上并不称这些为打包转换和解包转换但它确实涉及包装和展开。来自C#5规范的4.1.10部分,或在线规范(重点是我的):

The C# spec doesn't actually call these "wrapping conversions" and "unwrapping conversions" but it does talk about wrapping and unwrapping. From section 4.1.10 of the C# 5 spec, or the online spec (emphasis mine):


一个实例,其中 HasValue 为false表示为null。空实例具有未定义的值。尝试读取空实例的 Value 会引发 System.InvalidOperationException 。访问可空实例的 Value 属性的过程称为 unwrapping
除了默认构造函数之外,每个可为空的类型 T?都有一个公共构造函数,该构造函数接受单个类型为 T 。给定类型 T 的值 x ,构造器调用形式为

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)

创建 T?的非空实例,其 Value 属性为 x 。为给定值创建可为null的类型的非null实例的过程称为 wrapping

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.

这篇关于什么是换行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆