Passing An Enum Type As An Argument? [duplicate]
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.
精彩评论