2010-07-07 22 views
4

在C#中,使用初始化語法,我可以說:是否可以使用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); 

它似乎應該工作,但我不能讓它做任何事情。

回答

7

幾乎有:

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

嘿,那是什麼! – 2010-07-07 16:29:34

+1

是的,'字符串'較少鍵入:-) – 2010-07-07 16:30:22

+0

這就是答案。 :) – 2010-07-07 16:30:56

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

,但我不知道你是否可以簡化任何進一步...

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"); 
+1

切肉刀,但如果你仍然想要有多個拆分字符串,那麼你將在同一條船。 – 2010-07-07 16:39:15

+0

也許不是,讓我再試一次.... – 2010-07-07 16:41:08

+0

這是我的首選方法。我幾乎總是做出類似於此的擴展方法,甚至爲StringSplitOptions使用可選參數。 – drharris 2010-07-07 16:41:58

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); 
相關問題