开发者

Passing An Enum Type As An Argument? [duplicate]

This question already has answers here: 开发者_如何学编程 Closed 11 years ago.

Possible Duplicate:

C# enums as function parameters?

I was wondering how I can pass an enum type as a method argument.

I'm trying to create a generic method that will take a combo box, and enum, and fill the combo box with each item of the enum.


I think this is best explained by an example:

Say you have an enum:

enum MyEnum
{
    One,
    Two,
    Three
}

You can declare a method like:

    public static void MyEnumMethod(Enum e)
    {
        var enumValues = Enum.GetValues(e.GetType());

        // you can iterate over enumValues with foreach
    }

And you would call it like so:

MyEnumMethod(new MyEnum());


Refering to Convert Enum To Dictionary:

public static IDictionary<String, Int32> ConvertEnumToDictionary<K>()
{
 if (typeof(K).BaseType != typeof(Enum))
 {
   throw new InvalidCastException();
 }

 return Enum.GetValues(typeof(K)).Cast<Int32>().ToDictionary(currentItem => Enum.GetName(typeof(K), currentItem));
}

Then you can fill your ComboBox with the returned dictionary items.

Refer to the following as well:

Dictionary enumeration in C#

Enum to dictionary


You can pass an enum generically like this:

private void Method(Enum tEnum)
{
    Enum.GetValues(tEnum.GetType());
}

And the GetValues will give you the values that are possible for that enum.

Usage would be a little odd:

Method(EnumType.Value)

so it might not fit as well as other ideas.


Using this method, you cann add any type of enum like this: AddItems(myCombobox, typeof(Options))

  public void AddItems (ComboBox cboBox, Type enumType)
  {
     cboBox.Items.AddRange(Enum.GetValues (enumType).Cast<object> ().ToArray ());
  }

  enum Options
  {
     Left, Right, Center
  }


You can use:

Enum.GetValues(typeof(MyEnumType))

and just populate the combo box items from that

Edit: and of course use reflection to get the enum type :)


you could maybe use a kind of generic enum helper like here : http://devlicious.com/blogs/christopher_bennage/archive/2007/09/13/my-new-little-friend-enum-lt-t-gt.aspx.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜