2012-08-09 95 views
2

我不能返回null,因爲我的Hlist是非空類型。我還能返回什麼來代替null?如果字符串在c中有空或空白,該如何返回false

HList findHListentry(string letter) 
{ 
    if (string.IsNullOrWhiteSpace(letter)) 
    { 
     HList result = listentry.Find(delegate(HList bk) 
         { 
          return bk.letter == letter; 
         }); 
     return result; 
    } 
    else 
    { 
     return ?; 
    } 
} 
+1

什麼是'HList'? – 2012-08-09 20:19:22

+0

如果'HList'是一個值類型,你可以使它成爲一個可爲空的值類型嗎? 'HList?'? – vcsjones 2012-08-09 20:19:28

+2

有點相關:根據問題標題,我認爲你的條件邏輯混淆了。 – Travis 2012-08-09 20:21:20

回答

1

如果輸入法真正不應null或空字符串,你可以拋出一個異常:

HList findHListentry(string letter) 
{ 
    if (string.IsNullOrWhiteSpace(letter)) 
     throw new ArgumentNullException("letter"); 

    HList result = listentry.Find(
     delegate(HList bk) 
     { 
      return bk.letter == letter; 
     } 
    ); 

    return result; 
} 

(請注意,我也扭轉了條件邏輯,因爲它聽起來像你尋找相反的問題標題)

你也可以看看Code Contracts驗證方法的先決條件,而不是手動檢查輸入和拋出異常。

5

改爲使用Nullable<HList>

HList? findHListentry(string letter) 
{ 
    /// 
    return null; 
} 
0

您有幾種選擇:

如果HList是一個結構:

  1. 它做成一個類這一翻譯。然後你可以返回null。
  2. 方法簽名更改爲HList? findHListentry(string letter)
4

有非空值類型處理的幾種方法:

  • 使用Nullable<HList>(速記名稱爲HList?)或
  • 定義「空」HList條目,類似微軟如何定義一個用於Guid
  • 讓你的方法返回bool代替HList,並通過out參數返回HList,它是在Dictionary.TryGetValue

做的方式使用特殊值:

struct HList { 
    public static HList Empty; 
    ... 
} 

if (...) { 
    return HList.Empty; 
} 

返回bool

bool findHListentry(string letter, out HList res) { 
    ... 
} 
0

如果你不想返回null,你可以創建一個靜態的HList實例來表明它是一個'空'值。

到EventArgs.Empty

public static readonly HList EmptyHList = new Hlist() { /* initialise */ };

0

一個實現類似的是提供非可空類型的空實例,並返回到位空的。以字符串爲例...雖然字符串是一個可爲空的類型。NET,它包含一個名爲空一個內置的,只讀的領域,所以用字符串,你可以這樣做:

if(mystring == null) 
{ 
    //My String Is Null 
} 

或者,你可以這樣做

if(mystring == String.Empty) 
{ 
    //My String is Empty 
} 

雖然它可能不是最好的方法,你可以爲你的類/結構添加一個空的HList實例。例如

HList findHListentry(string letter) 
{ 
    if (string.IsNullOrWhiteSpace(letter)) 
    { 
     HList result = listentry.Find(delegate(HList bk) { return bk.letter == letter; }); 
     return result; 
    } 
    else 
    { 
     return HList.Empty; 
    } 
} 

public struct HList 
{ 
    public const HList Empty; 
} 

現在你可以在空的地方做這個

if(myHList == HList.Empty) 
{ 
    //My HList is Empty 
}