2013-11-04 63 views
0

在我的應用程序中,我添加了一個Properties.cs文件,其中包含我將在整個應用程序中使用的屬性。我得到的NullReferenceException =>Object reference not set to an instance of an object.屬性製造麻煩

這裏是Properties.cs

public class Properties 
{ 
    private static string type1; 

    public static string Type1 
    { 
     get 
     { 
      return type1; 
     } 
     set 
     { 
      type1= value; 
     } 
    } 
} 

的代碼,當我在我的形式之一訪問該屬性我得到的錯誤。例如

if (Properties.Type1.Equals(string.Empty) || Properties.Type1.Equals(null)) 
{ 
    // Do something 
} 
+1

好吧,是'Type1'集,或者它仍然有默認的'空'價值? –

+4

使用'string.IsNullOrEmpty' – Charleh

+0

檢查'Properties!= null'和'Type1!= null'太! – Belogix

回答

5

首先,你爲自己而努力。這是罰款(或者至少,只是很好,但容易得多;是否靜態成員是一個好主意是一個單獨的問題,很大程度上取決於上下文):

public class Properties 
{ 
    public static string Type1 { get;set; } 
} 

其次,這與屬性無關,以及在調用null實例上的方法時所做的一切。你可以只用==避免了這個問題,即

if (Properties.Type1 == "" || Properties.Type1 == null) 
{ 
    // Do something 
} 

然而,爲了方便也有string.IsNullOrEmpty

if (string.IsNullOrEmpty(Properties.Type1)) 
{ 
    // Do something 
} 
+1

它應該首先檢查'null'if'(Properties.Type1 == null || Properties.Type1 == string。空)',因爲它會在字符串檢查時拋出一個異常,如果它是'null'? – Belogix

+0

如果您在代碼Marc中顯示的第一個空字符串或null檢查無關緊要,它將以任何方式工作。然而,你不能「點」進入字符串,但他沒有這樣做。 –

+0

我正在爲物業分配價值,例如Types.Type1 =「abc」;但會出現NullReferenceException。那有什麼問題。 – DhavalR

2

使用這個代替:

if (string.IsNullOrEmpty(Properties.Type1)) 
{ 
    // Do something 
} 
+0

當我Types.Type1 =的東西再次出現NullReferenceException。如何設置它。 – DhavalR

+0

「類型」?那是什麼?你只顯示了類「Properties」的實現。如果僅僅指定屬性,那麼在問題中顯示的代碼中無法獲得'NullReferenceException'。 –

2

你正在做的方式是錯誤的零和空管檢查。

正確的方法是:

if (string.IsNullOrEmpty(Properties.Type1)) 
{ 
.... 
} 
0

你可以做到這一點

if (String.IsNullOrEmpty(Properties.Type1)) 
{ 
    // Do something 
} 

,但如果你想爲這個默認值,那麼我建議你把它在一個靜態構造函數。