I've searched (maybe not enough) but couldn't find an answer.
I want to make a generic function where I can pass any enum to use with a CheckedListBox
(get or set the value).
public enum TypeFlags
{
None = 0x0,
//List of flag
}
private void makeFlagOrBitmask(CheckedListBox list, Type e)
{
int myFlags = 0x0;
//I want to achieve something like that
foreach (Object item in list.CheckedItems)
{
//(TypeFlags)Enum.Parse(typeof(TypeFlags), item);
//So e should be the enum himself, but i can't figure how to do that
myFlags += (int)((e)Enum.Parse(typeof(e), item.tostring()));
}
}
So, I can make/read any flags with a single function.
The problem is that I can't figure out how to pass the enum as I need it in the function.
might not be complete but it sounds like you need a generic Enum iterator. I picked up the below code from Create Generic method constraining T to an Enum
public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
//...
}
I know this is not a nice Code but this works for me:
If the method want an object instead of a type (maybe you can do this with a type) you can do it like this:
if (e.GetType() == typeof(ImageType))
{
ValueArray = GetEnumArray(ImageType.Bmg);
}
This way you can check what Enum it es before you do something.
I hope this can help you.
You want to change this line:
myFlags += (int)((e)Enum.Parse(typeof(e), item.tostring()));
Into this:
myFlags += (int)((e)Enum.Parse(e, item.tostring()));
Since e
is already a type. As of how to pass the parameter:
makeFlagOrBitmask(myCheckBoxList, typeof(myEnum));
I hope this helps.
EDIT:
To make sure only enums will work, add this to the top of your function:
if (!e.IsEnum)
return;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.