简体   繁体   中英

Initialising a BindingList with enum values

I'm trying to initialise a BindingList with the values of an enumeration. According to MSDN BindingList there is a constructor that accepts an IList as a parameter.
My current code works, but seems rather "clunky":

list = new BindingList<Option>();
foreach (Option o in Enum.GetValues(typeof(Option)))
{
   list.Add(o);
}

I tried to use this code instead:

list = new BindingList<Option>(Enum.GetValues(typeof(Option)));

but it gave me an error saying it had invalid arguments, even though the return type of Enum.GetValues is Array, which implements IList.
If that constructor essentially does the same thing I do, I would still prefer using the constructor for readability purposes.

I would love if someone could point me to the right way of using this constructor for future use.

This should work for you:

var list = new BindingList<Option>(Enum.GetValues(typeof(Option)) as IList<Option>);

Edit based on your comment:

Although I have no clue why you why you would want to add or remove from a list of enum values, you could do so as follows:

var list = new List<Option>(Enum.GetValues(typeof(Option)) as IEnumerable<Option>);
/* Add anything you want to 'list' here */
var blist = new BindingList<Option>(list as IList<Option>);
/* blist is not readonly any more, so add or remove whatever you want */

The reason it was readonly is because BindingList is cloning the values from an enum. Considering you can't add or remove values from an enum, it makes perfect sense that the Array from Enum.GetValues(), and subsequently the IList that gets passed into BindingList's constructor is readonly. Because BindingList accepts an IList as the starting values, and not just an IEnumberable source, all of the properties of the IList are also cloned into the BindingList, not just the values themselves.

Hope that clarifies why the list was read-only. Although, you may want to reconsider why you need to add to a list of enum values.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM