2016-11-04 16 views
-1

我有很多像這樣的字符串變量;如何縮短C#中方法的用法?

string x1, x2, x3, x4, x5, x6, x7, x8; 

是否有可能縮短這段代碼

method(x1); 
method(x2); 
method(x3); 
method(x4); 
method(x5); 
method(x6); 
method(x7); 
method(x8); 

這樣我就可以使用這樣的事情,而不是(這下面不工作):

for(int i = 1; i <= 8; i++) 
{ 
    method("x" + i); 
} 

提前感謝!

+5

foreach語句?這聽起來像你應該使用一個列表。 –

+0

你可以使用反射,但這似乎是矯枉過正。 –

+0

將所有x變量放在列表中,並遍歷該列表 – TankorSmash

回答

4

使用數組所有這些字符串:

string[] data = new [] 
{ 
    "string1", 
    "string2", 
    "string3", 
    "string4", 
    x1, 
    x2, 
    x3, 
    x4 
}; 

foreach(var item in data) 
{ 
    method(item); 
} 

使用數組是一樣的,只是有陣列的集合:

var data = new List<string[]> 
{ 
    new [] {"1","2","3"}, 
    new [] {"a","b","c"}, 
}; 

foreach(var item in data) 
{ 
    method2(item); //notice that this method must get as a parameter a string[] 
} 
+0

是否可以對數組做同樣的操作?例如。 string [] x1; string [] x2; (x1); 然後 方法(x1);方法(x2); – CraftMine3001

+0

@ CraftMine3001 - 查看更新 –

+0

你喜歡髒碼;) –

0

根據吉拉德的回答,您可以使用列表和foreach:

var data = new List<string> 
{ 
    "string1", 
    "string2", 
    "string3", 
    "string4", 
    x1, 
    x2, 
    x3, 
    x4 
}; 

data.ForEach(x => method(x)); 

甚至更​​短:

data.ForEach(method); 
+0

值得一提的是'.ForEach'是'列表'的一種方法(只是一個小的更正,它不是linq的一部分,只是List的一個方法) –

+1

謝謝@Gilad Green你是對的 – meJustAndrew

1

其他答案顯示如何遍歷值並調用每個值的方法。如果您可以重寫該方法,則可以選擇讓它接受多個參數。

static void YourMethod(params string[] values) 
{ 
    foreach (var value in values) 
    { 
     // Do your work 
    } 
} 

您可以使用它像這樣:

YourMethod(x1, x2, x3, x4); 
0

您可以使用前面提到的foreach循環,或看起來更加乾淨,以我的方式,使用Extension Method爲你的對象類型使用。這非常好,特別是如果你使用這種方法很多,但無論如何它都可以工作。

static class Program 
{ 
    static void Main() 
    { 
     int[] test = { 1, 12, 13, 11, 31, 41, 21}; 
     test.CycleArray(); 
    } 
    public static void CycleArray(this int[] myArr) 
    { 
     if (myArr.Length > 0) 
      foreach (int x in myArr) 
       Console.WriteLine(x); 
    } 

然後就可以調用該類型的任何對象的方法,而不必再編寫代碼。

test.CycleArray(); 

每次你得到int []類型的對象,而無需額外的代碼將工作。

這是如果你不願意使用LINQ的方式。在這種情況下,最後

MyArray.ForEach(x => x+="i"); 

會做在一個單一的線一樣,假設你的代碼無法正常工作,如你所說。可以

0

您的字符串和行動類似下面

Dictionary<string, Action<string>> _mapOfMethods = new Dictionary<string,Action<string>> { { "TestString1", Method1 }, {"TestString2", Method2 }}; 

一個字典,你爲什麼擺在首位所有這些變量,你可以使用如下

 foreach (var item in _mapOfMethods) 
     { 
      item.Value(item.Key); 
     }