如何创建支持空值的结构?
我是 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过使用 Generic Nullable<> 可以使结构和值类型可为空。类来包装它。例如:
C# 为此提供了一种语言功能,方法是在类型后面添加问号:
Same 应该适用于包括结构在内的任何值类型。
MSDN 说明: 可空类型 (c#)
Structs and value types can be made nullable by using the Generic Nullable<> class to wrap it. For instance:
C# provides a language feature for this by adding a question mark after the type:
Same should work for any value type including structs.
MSDN Explanation: Nullable Types (c#)
您可以使用
Nullable
,它在 C# 中有一个别名。请记住,结构本身并不是真正的 null(编译器在幕后以不同的方式对待 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.As @CodeInChaos mentions
Nullable<T>
is only boxed when it is in a non-null state.Nullable Types
Boxing Nullable Types
您可以使用
Nullable
对于结构,或相同的简写形式 (?):you can use
Nullable<T>
for structs, or the shorthand form (?) of the same:由于“Struct”不是引用类型,因此您不能像往常一样分配“null”。所以您需要使用以下形式来使其“可为空”
[结构名称]? [变量名称] = 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.
then you can assign null for the object and also check the nullability using conditional statements.