2

対応する 3 つの列挙型の値を 3 つのリスト ボックスに入力しています。3 つの別個の非常に類似した方法を回避する方法はありますか? これが私が今持っているものです:

    private void PopulateListBoxOne()
    {
        foreach (EnumOne one in Enum.GetValues(typeof(EnumOne)))
        {
            lstOne.Items.Add(one);
        }
        lstOne.SelectedIndex         = 0;
    }

    private void PopulateListBoxTwo()
    {
        foreach (EnumTwo two in Enum.GetValues(typeof(EnumTwo)))
        {
            lstTwo.Items.Add(two);
        }
        lstTwo.SelectedIndex         = 0;
    }

    private void PopulateListBoxThree()
    {
        foreach (EnumThree three in Enum.GetValues(typeof(EnumThree)))
        {
            lstThree.Items.Add(three);
        }
        lstThree.SelectedIndex         = 0;
    }

しかし、代わりに、次のような 1 つのメソッド (3 回呼び出すことができる) を使用することをお勧めします。

private void PopulateListBox(ListBox ListBoxName, Enum EnumName)
{
    // ... code here!
}

私はかなり経験の浅いプログラマーなので、検索はしましたが、何を検索しているのかよくわかりませんでした。これが以前に回答されている場合はお詫びします。既存の回答が表示されることにも同様に感謝します。ありがとう!

4

3 に答える 3

5

メソッドに列挙型を渡す必要があります

private void PopulateListBox(ListBox ListBoxName, Type EnumType)
{
    foreach (var value in Enum.GetValues(EnumType))
    {
        ListBoxName.Items.Add(value);
    }
    ListBoxName.SelectedIndex=0;
}

次のように呼び出します。

PopulateListBox(lstThree,typeof(EnumThree));
于 2013-10-10T11:01:42.060 に答える
3

一般的な方法を使用できます:

private void PopulateListBox<TEnum>(ListBox listBox, bool clearBeforeFill, int selIndex) where TEnum : struct, IConvertible
{
    if (!typeof(TEnum).IsEnum)
        throw new ArgumentException("T must be an enum type");

    if(clearBeforeFill) listBox.Items.Clear();
    listBox.Items.AddRange(Enum.GetNames(typeof(TEnum))); // or listBox.Items.AddRange(Enum.GetValues(typeof(TEnum)).Cast<object>().ToArray());

    if(selIndex >= listBox.Items.Count)
        throw new ArgumentException("SelectedIndex must be lower than ListBox.Items.Count");

    listBox.SelectedIndex = selIndex;
}

使用方法:

PopulateListBox<EnumThree>(lstThree, true, 0);
于 2013-10-10T11:05:49.107 に答える
0

次のようなものを試すことができます

    private List<T> PopulateList<T>()
    {
        List<T> list = new List<T>();
        foreach (T e in Enum.GetValues(typeof(T)))
        {
            list.Add(e);
        }
        return list;
    }
于 2013-10-10T11:04:13.003 に答える