如何创建支持空值的结构?

发布于 2024-11-18 15:52:26 字数 57 浏览 3 评论 0原文

我是 C# 新手。在 C# 中,我无法将结构的值设置为 null 如何创建支持 null 值的结构?

I'm new in C#. In c# I can't set value of a structure to null how can I create a structure with null value support?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

优雅的叶子 2024-11-25 15:52:26

通过使用 Generic Nullable<> 可以使结构和值类型可为空。类来包装它。例如:

Nullable<int> num1 = null;

C# 为此提供了一种语言功能,方法是在类型后面添加问号:

int? num1 = null;

Same 应该适用于包括结构在内的任何值类型。

MSDN 说明: 可空类型 (c#)

Structs and value types can be made nullable by using the Generic Nullable<> class to wrap it. For instance:

Nullable<int> num1 = null;

C# provides a language feature for this by adding a question mark after the type:

int? num1 = null;

Same should work for any value type including structs.

MSDN Explanation: Nullable Types (c#)

最近可好 2024-11-25 15:52:26

您可以使用 Nullable,它在 C# 中有一个别名。请记住,结构本身并不是真正的 null(编译器在幕后以不同的方式对待 null)。它更像是一种选项类型

Struct? value = null;

正如@CodeInChaos提到的,Nullable仅在处于非空状态时才被装箱。

可空类型

装箱可空类型

You can use Nullable<T> which has an alias in C#. Keep in mind that the struct itself is not really null (The compiler treats the null differently behind the scenes). It is more of an Option type.

Struct? value = null;

As @CodeInChaos mentions Nullable<T> is only boxed when it is in a non-null state.

Nullable Types

Boxing Nullable Types

猫腻 2024-11-25 15:52:26

您可以使用 Nullable对于结构,或相同的简写形式 (?):

表示一个对象,其底层
type 是一个值类型,也可以是
像引用类型一样分配 null。

struct Foo
{
}

Nullable<Foo> foo2 = null; 
Foo? foo = null; //equivalent shorthand form

you can use Nullable<T> for structs, or the shorthand form (?) of the same:

Represents an object whose underlying
type is a value type that can also be
assigned null like a reference type.

struct Foo
{
}

Nullable<Foo> foo2 = null; 
Foo? foo = null; //equivalent shorthand form
旧瑾黎汐 2024-11-25 15:52:26

由于“Struct”不是引用类型,因此您不能像往常一样分配“null”。所以您需要使用以下形式来使其“可为空”

[结构名称]? [变量名称] = null

例如。

Color? color = null;

然后您可以为该对象分配 null 并使用条件语句检查可空性。

Since the "Struct" is not a reference type, you cannot assign "null" as usual manner. so you need to use following form to make it "nullable"

[Struct Name]? [Variable Name] = null

eg.

Color? color = null;

then you can assign null for the object and also check the nullability using conditional statements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文