0

Let's say I have the following code:

private void btnArr1(object sender, EventArgs e)
{
    wr("test string1","st1");
}
private void btnArr2(object sender, EventArgs e)
{
    wr("test string2","st2");
}
private void btnArr3(object sender, EventArgs e)
{
    wr("test string3","st3");
}

private void wr(String str, String st){
    switch(st){
        case "st1":{
            st1.Add(str);
            break;
        }
        case "st2":{
            st2.Add(str);
            break;
        }
        case "st3":{
            st3.Add(str);
            break;
        }
    }       
}

Is it somehow possible to minimize that code?

For example Change "st1.Add(str)" to something like "st".Add(str).

The only difference between those buttons is the list name where the information is stored. Everything else is equal.

4

3 回答 3

2

您需要使用Dictionary<String, List<String>>.

在您的构造函数(或其他初始化区域)中,new List<string>()为您需要的每个键添加一个。

然后你可以写

 dict[someKey].Add(something);
于 2013-02-22T17:44:43.280 回答
1

好吧,如果这些都在同一个类中,您可以使用:

private void btnArr1(object sender, EventArgs e)
{
    st1.Add("test string1");
}

private void btnArr2(object sender, EventArgs e)
{
    st2.Add("test string2");
}

private void btnArr3(object sender, EventArgs e)
{
    st3.Add("test string3");
}

如果这对您不起作用,请详细说明为什么它不起作用。

于 2013-02-22T17:44:27.550 回答
1

st1在不知道,等的类型的情况下很难说st2,但是像这样?

private void btnArr1(object sender, EventArgs e)
{
    wr("test string1",st1);
}
private void btnArr2(object sender, EventArgs e)
{
    wr("test string2",st2);
}
private void btnArr3(object sender, EventArgs e)
{
    wr("test string3",st3);
}

private void wr(String str, List<string> st){
     st.Add(str);
}
于 2013-02-22T17:45:42.970 回答