Create Non-Nullable Types in C#

跟風遠走 提交于 2019-11-27 13:25:20

问题


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


回答1:


Yes, these are called struct.

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

They have some rules/recommendations related to them: (I think these are the most important)

  • 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.

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

  • 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.




回答2:


7 years later and this is now possible

  • Install .NET Core 3.0 which includes C# 8.
  • Set the language version to 8.0: 8.0 to your .csproj file.
  • Add the property true (.to your csproj)

More details on his this affects writing code and your existing code here:

https://praeclarum.org/2018/12/17/nullable-reference-types.html




回答3:


You can define a struct:

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;
}

However, you can't define aliases like int for System.Int32 and need to refer with the full name MyNamespace.Book (or Book with using MyNamespace;) to your struct.



来源:https://stackoverflow.com/questions/6365459/create-non-nullable-types-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!