如何在C#中创建类似int、bool等非空值类型?
是的,这些被称为struct
。
struct
是值类型,就像int
,bool
和其他类型一样。
它们有一些与之相关的规则/建议:(我认为这些是最重要的)
在不使用ref或out关键字时,结构体是按值传递和赋值的...这意味着当将其分配或传递给方法时,放入结构体中的所有内容都将被复制。这就是为什么不应该创建大型结构体。
在C#中,无法为结构体定义无参数构造函数。
最好将struct
定义为不可变类型,并且没有属性设置器。通过创建可变的结构体,可能会遇到真正的麻烦。
关于struct
的其他规则可以在 Microsoft 文档中找到。
至于非空引用类型......这是不可能的。你必须在代码中手动检查空值。
7年后,现在可以做到这一点了。
<LangVersion>8.0</LangVersion>
添加到你的.csproj文件中。<NullableReferenceTypes>true</NullableReferenceTypes>
(到你的.csproj文件中)有关如何编写代码以及如何影响您现有代码的更多详细信息,请参见此处:
https://praeclarum.org/2018/12/17/nullable-reference-types.html
<LangVersion>8.0</LangVersion> <NullableReferenceTypes>true</NullableReferenceTypes>
- deadlydog然而,您不能像为 System.Int32 定义 int 别名一样,需要使用完整名称 MyNamespace.Book(或使用 using MyNamespace; 后的 Book)来引用您的结构体。A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:
public struct Book { public decimal price; public string title; public string author; }
MyType type;
在开始时将为null。 - Marino Šimićoption<string>
),因此您可以通过编译时的类型系统来通信和强制执行空值检查。参见https://dev59.com/5kbRa4cB1Zd3GeqP4d1L#1451909。 - Juliet