C#创建非空类型 [英] Create Non-Nullable Types in C#

查看:110
本文介绍了C#创建非空类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#创建非空值类型如int,布尔等?

How to create non-nullable value types like int, bool, etc. in C#?

推荐答案

是的,这些都是名为结构

结构是值类型,就像 INT 布尔

Structs are value types, just like int, bool and others.

他们有与之相关的一些规则/建议:(我认为这些是最重要的)


  • 一个结构传递和价值分配的,当不使用ref或出关键字...这意味着你一个结构里面把一切都将分配或传递给一个方法时被复制。这就是为什么你不应该让大的结构。

  • a struct is passed and assigned by value, when not using ref or out keywords... this means that everything you put inside a struct will be copied when assigning or passing it to a method. That is why you should not make large structs.

您不能定义在C#中的结构

you cannot define a parameterless constructor for a struct in C#

结构是更好的为不可变的,并且没有属性setter。您可以通过可变结构陷入真正的麻烦。

structs are better to be immutable, and have no property setters. You can get into real trouble by making mutable structs.

其他规则,可结构微软文档中找到。

Other rules can be found within Microsoft docs about structs.

至于非空的引用类型 ...这就是无法。你必须检查你的代码中的空值,手动。

As for non-nullable reference types... this is not possible. You must check for nulls inside your code, manually.

这篇关于C#创建非空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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