是否可以使用C#初始化语法来传递参数?

时间:2010-07-07 16:26:49

标签: c# c#-4.0

在C#中,使用初始化语法我可以说:

string[] mystrings = {"one", "two", "three"};

是否可以使用相同的数组初始化语法来转换它:

string test = "This is a good sentance to split, it has at least one split word to split on.";
string[] mystrings = test.Split(new string[] { "split" }, StringSplitOptions.RemoveEmptyEntries);

这样的事情:

string test = "This is a good sentance to split, it has at least one split word to split on.";
string[] mystrings = test.Split({ "split" }, StringSplitOptions.RemoveEmptyEntries);

它似乎应该可行,但我无法做任何事情。

4 个答案:

答案 0 :(得分:7)

几乎就在那里:

string[] mystrings = test.Split(new[]{ "split" }, 
    StringSplitOptions.RemoveEmptyEntries);

答案 1 :(得分:2)

您似乎需要新的string方法:

public static class StringExtensions {
  public static string[] Split(this string self, string separator, StringSplitOptions options) {
    return self.Split(new[] { separator }, options);
  }
}

像这样使用:

string[] mystrings = test.Split("split", StringSplitOptions.RemoveEmptyEntries);

现在,由你决定是否值得介绍它。

对于多个分隔符,您可以修复options参数(或将其放在前面,根据其他“重载”会感觉不自然):

public static class StringExtensions {
  // maybe just call it Split
  public static string[] SplitAndRemoveEmptyEntries(this string self, params string[] separators) {
    return self.Split(separators, StringSplitOptions.RemoveEmptyEntries);
  }
}

用法:

string[] mystrings = test.SplitAndRemoveEmptyEntries("banana", "split"); 

答案 2 :(得分:1)

您当然可以使用以下语法:

string test = "This is a good sentance to split, it has at least one split word to split on.";
string[] mystrings = test.Split(new[] { "split" }, StringSplitOptions.RemoveEmptyEntries);

但我不确定你是否可以进一步简化......

答案 3 :(得分:0)

您可以添加扩展方法:

    public static String[] Split(this string myString, string mySeperator, StringSplitOptions options)
    {
        return myString.Split(new[] {mySeperator}, options);
    }

然后你可以这样做:

    string test = "This is a good sentance to split, it has at least one split word to split on.";
    string[] mystrings = test.Split("split", StringSplitOptions.RemoveEmptyEntries);