首页 > 解决方案 > 如何在c#中将值类型设置为null?

问题描述

我目前正在尝试设置一个为空的 int,类似于字符串可以为空的方式。我试过: int i = null; 返回Cannot convert null to 'int' because it is a non-nullable value type但字符串 s = null; 完全没问题。

标签: c#

解决方案


因此默认情况下值类型不能设置为 null,但是有一些方法可以将它们设置为 null。要解决您的问题,您需要这样做: int? i = null;

这来自此处的 Microsoft 文档: https ://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/

值类型与引用类型可以在这里找到: https ://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type


推荐阅读