2017-04-08 96 views
0

我试图在一个项目上工作,我想要一个可为空的属性。创建一个可为空的对象。可以做到吗?

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 { 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? NullableClass

当我谷歌他们不说,为什么这不能做,但他们也没有说如何做到这一点。

所以我的问题是以下。 我可以创建可为空的对象吗? 是吗? - >如何? 不是吗? - >为什么不呢?

+1

引用类型已经_nullable_ –

回答

1

C#中的类默认为空类型。因为它实际上是一个可以设置为空的指针。

C#中的另一个对象类型是Struct,它不能为空,并且用值而不是引用来处理。简单类型如intbool是结构。你可以像一个类一样定义一个结构体。

Struct中搜索更多,你会看到的。

你的情况,你可以有:

public struct NullableStruct 
{ 
    public Guid ID { get; set; } 
    public string Name { get; set; } 
} 

而且它将很好地工作NullableStruct?

+2

不能为结构定义参数构造函数。 – Lee

+1

@Lee您可以但需要使用数据初始化其中的所有属性。 – Emad

+0

非常感谢你们!我忘记了C#也有结构xD – StuiterSlurf