【问题标题】:Is there a way to convert between a collection of custom enum to a collection of another custom enum?有没有办法将自定义枚举集合转换为另一个自定义枚举集合?
【发布时间】:2018-07-12 13:46:26
【问题描述】:

我们已经知道我们可以convert an enum to another type of enum,所以以下编译:

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
   }
}

但这不能编译:

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
   }
}

这是covariance 的问题吗?如果没有,有没有办法让它工作?

【问题讨论】:

  • 您是否期望Enum1,Foo 始终等同于Enum2.Foo?如果Enum1.Foo 等于整数 1 而Enum2.Foo 等于整数 2 会怎样?

标签: c# collections enums


【解决方案1】:

这不是 co-variance 问题,而是 variance 问题。枚举是值类型,值类型不支持协方差。而List&lt;T&gt;class,而不是interfacedelegate。仅接口和委托支持协变。

您必须转换/转换列表中的元素:

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

但这当然会产生一个新列表。 eListlist2 是不同的实例。

【讨论】:

    【解决方案2】:

    你不能那样投,Enum1Enum2 是完全不同的东西。不过,您可以使用一些简单的 Linq 来完成。例如:

    List<Enum2> eList = new List<Enum2>
    { 
        Enum2.Foo 
    };
    
    List<Enum1> e1List = eList
        .Select(x => (Enum1)x)
        .ToList();
    

    请注意,这是使用直接大小写,但您可能希望使用您链接的问题中的转换函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多