简体   繁体   English

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

[英]Is it possible to use C# Initialization Syntax to pass a parameter?

In C#, using the initialization syntax I can say: 在C#中,使用初始化语法我可以说:

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

Is it possible to use the same array initialization syntax to convert this: 是否可以使用相同的数组初始化语法来转换它:

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);

Into something like this: 进入这样的事情:

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);

It seems like it should work but I can't get it to do anything. 它似乎应该工作,但我不能让它做任何事情。

Almost there: 快好了:

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

Looks like you need a new string method: 看起来你需要一个新的string方法:

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

Use it like this: 像这样使用它:

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

Now, it's up to you to decide if it's worth or not to introduce it. 现在,由您决定是否值得介绍它。

For multiple separators, you can fix the options parameter (or put it in front, which will feel unnatural based on the other "overloads"): 对于多个分隔符,您可以修复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);
  }
}

And the usage: 用法:

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

You can certainly have this syntax: 你当然可以有这样的语法:

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);

but I am not sure if you can simplify it any further... 但我不确定你是否可以进一步简化它......

You could add an extension method: 您可以添加扩展方法:

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

Then you can do: 然后你可以这样做:

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM