C# 创建一个可为空的对象。能做到吗?
我试图在一个项目上工作,我想要一个可为空的属性 NullableClass.csC# 创建一个可为空的对象。能做到吗?,c#,C#,我试图在一个项目上工作,我想要一个可为空的属性 NullableClass.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class NullableClass { public Guid ID
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class NullableClass
{
public Guid ID { get; set; }
public string Name { get; set; }
public NullableClass()
{ }
public NullableClass(string Name)
{
this.Name = Name;
}
}
}
MainClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class MainClass
{
public Guid ID { get; set; }
public string Name { get; set; }
puplic int? Number { get; set; }
public NullableClass? NullableClass { get; set; }
public MainClass()
{ }
public MainClass(string Name)
{
this.Name = Name;
}
}
}
Visual studio出现以下错误:
The type 'NullableClass' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>'
类型“NullableClass”必须是不可为null的值类型,才能将其用作泛型类型或方法“nullable”中的参数“T”
如何使我的属性为NullableClass?空类
当我在谷歌上搜索时,他们没有说为什么不能做到,但也没有说如何做到
因此,我的问题如下。
我可以创建可为空的对象吗?
是吗?->怎么用?
没有?->为什么不呢?C#中的类默认为可空类型。因为它实际上是一个可以设置为null的指针
C#中的另一个对象类型是Struct
,它不可为null,并且使用值而不是引用来处理。像int
和bool
这样的简单类型是结构。您可以像定义类一样定义结构
更多地搜索Struct
,您将看到
在您的情况下,您可以:
public struct NullableStruct
{
public Guid ID { get; set; }
public string Name { get; set; }
}
它可以与
NullableStruct?
引用类型已经为Nullable。您不能为结构定义无参数构造函数。@Lee您可以,但您需要用数据初始化其中的所有属性。非常感谢大家!我忘了C#也有结构XD不,你不能,即使你正确地命名构造函数并在字符串构造函数中分配ID
,你的例子也无法编译。@StuiterSlurf说得很清楚,Lee关于结构不能有无参数构造函数的评论是正确的,但你的评论遗漏了这一个词,弄错了。结构可以有构造函数,只要这些构造函数有参数。