简体   繁体   English

如何转换IEnumerable <MySpecificEnumType> 通用IEnumerable <Enum> 在WPF(C#)中

[英]How to convert IEnumerable<MySpecificEnumType> to generic IEnumerable<Enum> in WPF (C#)

I have a user control that uses a combobox with its source being bound to an IEnumerable of type Enum (I have several different types of user defined enums to be used in the user control, so use the generic IEnumerable<Enum> in the backing code of my user control). 我有一个使用组合框的用户控件,其组合源绑定到Enum类型的IEnumerable (我在用户控件中使用了几种不同类型的用户定义枚举,因此请在支持代码中使用通用IEnumerable<Enum>我的用户控件)。 However, when I attempt to create the IEnumberable list in the backing code of the item using the user control, I can't convert my IEnumerable of my own enum type to the generic Enum IEnumerable . 但是,当我尝试使用用户控件在项目的支持代码中创建IEnumberable列表时,无法将我自己的枚举类型的IEnumerable转换为通用的Enum IEnumerable

I get the following error: 我收到以下错误:

Unable to cast object of type MyEnumType[] to type System.Enum[] when I attempt to convert to Enum[] . 当我尝试转换为Enum[]时,无法将MyEnumType[]类型的对象转换为System.Enum[]类型。 The code giving this error is: 给出此错误的代码是:

public IEnumberable<Enum> MyEnums { get { return (Enum[])Enum.GetValues(typeof(MySpecificEnumType)); } }

How should I convert from a list of my enum type to a list of the generic Enum type? 我应该如何从枚举类型的列表转换为通用Enum类型的列表? Or should I be using a different type of IEnumerable in the backing code of my user control? 还是应该在用户控件的备用代码中使用其他类型的IEnumerable

如果您确实希望获得IEnumerable<Enum> ,则可以使用Cast扩展方法:

return Enum.GetValues(typeof(MySpecificEnumType)).Cast<Enum>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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