使用初始化列表从数组初始化列表
基类具有 List
类型的 readonly 字段,派生类将对其进行初始化。现在,有一个派生类,我想在其中添加 SomeEnum 的所有值。一种方法是输入所有枚举值,但是枚举有点大,那么还有其他方法吗?
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)) }
{
}
}
(上面的代码无法编译,我相信初始化器不接受数组。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是因为您必须将 Enum.GetValues 的结果转换为适当的 IEnumerable。类型。参见这里:
It's because you have to cast the result of Enum.GetValues to the appropriate IEnumerable<T> type. See here:
正如 Mark 所写,有一个 List 构造函数接受可枚举的值,也许您可以通过以下(较少耦合)的方式利用它:
As Mark wrote, there is a List constructor that accepts an enumerable, maybe you can leverage it the following (less coupled) way:
这是行不通的,因为集合初始值设定项会使用您的参数调用
Add
,并且您无法使用Add
方法将数组添加到列表中(您需要 <改为代码>AddRange)。但是,有一个
List构造函数 code> 可以接受
IEnumerable
。试试这个:That won't work because the collection initializer calls
Add
with your argument, and you can't add an Array to a List using theAdd
method (you'd needAddRange
instead).However there is a constructor for
List<T>
can acceptIEnumerable<T>
. Try this:您是否尝试过在列表的构造函数中传递值数组,如下所示:
Did you tried passing the array of values in the constructor of the list, like this:
我通过将枚举器返回到通用类型(List 接受的类型)来使其工作。
I got it working by casting the enumerator returned to the generic type (which List accepts.)