[英]convert an array of enums into a generic array of enums
How can I convert an array of enums into a generic array of enums in c#. 如何将枚举数组转换为c#中的通用枚举数组。
To be clear: 要明确:
Given: 鉴于:
public enum PrimaryColor
{
red = 0,
blue = 1,
yellow = 3
}
public enum SecondaryColor
{
green = 0,
purple = 1,
orange = 2
}
I want to do something like this: 我想做这样的事情:
public class MyClass
{
public static void Main()
{
PrimaryColor[] pca = {PrimaryColor.blue, PrimaryColor.yellow};
SecondaryColor[] sca = {SecondaryColor.purple, SecondaryColor.orange};
Enum[] enumArray = pca;
}
}
which leads to a compiler error of: 这导致编译器错误:
Cannot implicitly convert type 'PrimaryColor[]' to 'System.Enum[]'
I could use linq or some more iterative process, but I wonder if there is a better cast I could use instead. 我可以使用linq或更多的迭代过程,但我想知道是否有更好的演员我可以使用。
You can do it iteratively only 你只能迭代地做
Enum[] enumArray = Array.ConvertAll(pca, item => (Enum)item);
Or (less efficient but Linq!) 或者(效率较低,但Linq!)
Enum[] enumArray = pca.Cast<Enum>().ToArray();
Why you can't simply cast arrays? 为什么你不能简单地投射数组? Because in C# covariance enabled only for arrays of reference types (enums are value types).
因为在C# 协方差中仅对引用类型的数组启用(枚举是值类型)。 So, with class
Foo
you can do: 因此,使用
Foo
类,您可以:
Foo[] foos = new Foo[10];
object[] array = (object[])foos;
PrimaryColor[] pca = { PrimaryColor.blue, PrimaryColor.yellow };
SecondaryColor[] sca = { SecondaryColor.purple, SecondaryColor.orange };
Enum[] enumArray = pca.Select(q => q as Enum).ToArray();
Or; 要么;
for (int i=0; i<pca.Count();i++)
{
enumArray[i] = pca[i];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.