2013-04-02 44 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。简单,干净,优雅。谢谢。 –

相关问题