2017-04-08 60 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

相關問題