2013-04-02 43 views
2

所以,也許我很累,但爲什麼我不能創建一個新的MatchCollection無法創建新的MatchCollection - 沒有定義構造函數

我有通過調用regex.Matches返回MatchCollection的方法:

public static MatchCollection GetStringsWithinBiggerString(string sourceString) 
{ 
    Regex regex = new Regex(@"\$\(.+?\)"); 

    return regex.Matches(sourceString); 
} 

我想要做的是返回一個空集,如果該參數爲空:

public static MatchCollection GetStringsWithinBiggerString(string sourceString) 
{ 
    if (sourceString == null) 
    { 
     return new MatchCollection(); 
    } 

    Regex regex = new Regex(@"\$\(.+?\)"); 

    return regex.Matches(sourceString); 
} 

但贏得」 t因爲這一行彙編:

return new MatchCollection(); 

錯誤:

The type 'System.Text.RegularExpressions.MatchCollection' has no constructors defined.

如何定義類型沒有構造函數?如果沒有明確定義構造函數,我認爲會創建一個默認的構造函數。是否無法爲我的方法返回MatchCollection創建新實例?

回答

2

How can a type have no constructors defined?

它不能。但它可以隱藏它的所有構造函數,使它們不公開 - 即私有,內部或受保護。而且,一旦定義了構造函數,默認構造函數就變得不可訪問。同一名稱空間中的其他類可以訪問內部構造函數,但名稱空間外部的類將無法直接實例化類。

P.S.如果你想創建一個空的匹配集合,你總是可以匹配的東西的表達,並通過別的東西:

Regex regex = new Regex(@"foo"); 
var empty = regex.Matches("bar"); // "foo" does not match "bar" 
+0

其實如果你定義一個參數的構造函數,你不能使用默認的構造函數了,除非你明確的聲明。 –

+0

+1。 Ahhhh ......沒有考慮到非公開的構造函數。哎呀。謝謝。所以我不能返回一個空的'MatchCollection',除非我在他的回答中提到的BrunoLM做一些變通? –

1

也許一個解決辦法:

如果sourceStringnull它設置爲""並繼續執行。

+0

+1。好的提示。謝謝! –

5

非常合適的使用Null Object模式!

實現這樣的:

public static MatchCollection GetStringsWithinBiggerString(string sourceString) 
{ 
    Regex regex = new Regex(@"\$\(.+?\)"); 

    return regex.Matches(sourceString ?? String.Empty); 
} 
+0

+1。簡單,乾淨,優雅。謝謝。 –

相關問題