简体   繁体   English

有没有一种方法可以在一个自定义枚举集合与另一个自定义枚举集合之间进行转换?

[英]Is there a way to convert between a collection of custom enum to a collection of another custom enum?

We already know we can convert an enum to another type of enum , so the following compiles: 我们已经知道可以将一个枚举转换为另一种枚举 ,因此可以进行以下编译:

public class EnumTest
{
   enum Enum1 { Foo };
   enum Enum2 { Foo };
   void Test () 
   {
       System.Enum e = new Enum2();   // compiles
       Enum1 e1 = (Enum1)new Enum2(); // compiles with an explicit cast
   }
}

But this doesn't compile: 但这不能编译:

public class EnumTest
{
   enum Enum1 { Foo };
   enum Enum2 { Foo };
   void Test () 
   {
       List<System.Enum> eList = new List<Enum2>();         // doesn't compile
       List<Enum1> e1List = (List<Enum1>)new List<Enum2>(); // doesn't compile
   }
}

Is that a covariance issue? 这是一个协方差问题吗? If not, is there a way to make it work? 如果没有,是否有办法使其起作用?

It's not a co -variance issue, it's a variance issue. 这不是方差问题,而是方差问题。 Enums are value types and co-variance is not supported for value types. 枚举是值类型,值类型不支持协方差。 And List<T> is a class , not an interface or delegate . List<T>是一个class ,而不是interfacedelegate Co-variance is only supported for interfaces and delegates. 协方差仅支持接口和委托。

You have to cast/convert the elements in the lists: 您必须转换/转换列表中的元素:

List<Enum2> list2 = ...
List<System.Enum> eList = list2.Cast<System.Enum>().ToList();

But this of course results in a new list. 但这当然会产生一个新列表。 eList is a different instance than list2 . eListlist2是不同的实例。

You can't cast like that, Enum1 and Enum2 are completely different things. 您不能像这样Enum2Enum1Enum2是完全不同的东西。 You can do it with some simple Linq though. 您可以使用一些简单的Linq来完成。 For example: 例如:

List<Enum2> eList = new List<Enum2>
{ 
    Enum2.Foo 
};

List<Enum1> e1List = eList
    .Select(x => (Enum1)x)
    .ToList();

Note this is using a straight case, but you might want to use the conversion function from the question you linked. 请注意,这使用的是简单的情况,但是您可能要使用链接的问题中的转换函数。

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

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