开发者

Initialize list from array using a initializer list

A base class have readonly field of type List<SomeEnum> which the derived classes will initialize. Now, there is a derived class in which I want to add the all the values of the SomeEnum. One way is to type all the enum values, but the enum is a little big, so is there any other way to do it?

public class Base
{
 private readonly List<SomeEnum> _list;

 protected Base(List<SomeEnum> list)
 {
  _list = list;
 }
}

public class Derived : Base
{
 public Derived() : base(new List<SomeEnum>() { Enum.GetValues(typeof(SomeEnum)) }
 {
 }
}

(The above code 开发者_如何转开发would not compile, I believe intializers don't accept arrays.)


It's because you have to cast the result of Enum.GetValues to the appropriate IEnumerable<T> type. See here:

using System.Linq;


public class Derived : Base
{
    public Derived()
        : base(new List<SomeEnum>(Enum.GetValues(typeof(SomeEnum)).OfType<SomeEnum>()))
    {
    }
}


As Mark wrote, there is a List constructor that accepts an enumerable, maybe you can leverage it the following (less coupled) way:

public class Base 
{     
  private readonly List<UserActions> _list;      

  protected Base(IEnumerable<UserActions> values)
  {         _list = new List<UserActions>(values);  
  } 
}  

public class Derived : Base 
{     
   public Derived() : base((UserActions[]) Enum.GetValues(typeof(UserActions))
  { 
  }
} 


That won't work because the collection initializer calls Add with your argument, and you can't add an Array to a List using the Add method (you'd need AddRange instead).

However there is a constructor for List<T> can accept IEnumerable<T>. Try this:

new List<SomeEnum>((IEnumerable<SomeEnum>)Enum.GetValues(typeof(SomeEnum)))


Did you tried passing the array of values in the constructor of the list, like this:

public Derived() : 
         base(new List<SomeEnum>(Enum.GetValues(typeof(UserActions))) 
{}


base(new List<SomeEnum>(((IEnumerable<SomeEnum>)Enum.GetValues(typeof(SomeEnum)).GetEnumerator())))

I got it working by casting the enumerator returned to the generic type (which List accepts.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜