2

我有一个枚举的扩展方法

public static IEnumerable<T> GetFlags<T>(this T value) where T : struct
    {
        CheckIsEnum<T>(true);
        foreach (T flag in Enum.GetValues(typeof(T)).Cast<T>())
        {
            if (value.IsFlagSet(flag))
                yield return flag;
        }
    }

我试图得到这样的结果:

Zone_Status_ZoneConditionFlagEnum flags = (Zone_Status_ZoneConditionFlagEnum)flagsRaw;

List<Zone_Status_ZoneConditionFlagEnum> ZoneConditionFlags_List = (List<Zone_Status_ZoneConditionFlagEnum>)flags.GetFlags();

但我明白了

NX584(NX584Test)->Error parsing message: Cannot implicitly convert type [Digicom.NX584Engine.Messages.Zone_Status_ZoneConditionFlagEnum] to System.Collections.Generic.List`1[Digicom.NX584Engine.Messages.Zone_Status_ZoneConditionFlagEnum].
4

3 回答 3

2

我不清楚您为什么会收到错误-但您不能将结果GetFlags<T>转换为 a List<T>,因为它不返回 a List<T>。最简单的解决方法是:

var ZoneConditionFlags_List = flags.GetFlags().ToList();

如果不起作用,请提供新的错误消息。

或者,您可以更改GetFlags它实际上返回 aList<T>而不是使用迭代器块。

于 2013-06-20T10:15:04.750 回答
1

The first issue here is that a sequence is different to a list; if you need a list, either return a list, or add .ToList() after GetFlags(), i.e.

var ZoneConditionFlags_List = flags.GetFlags().ToList();

However, the bigger problem is that you can't use that IsFlagSet in that generic context; that method is not defined for an arbitrary T : struct.

Personally, I think you'd be better just to treat it as a [Flags] enum throughout; I assume you have existing code that wants a list rather than a single value?

于 2013-06-20T10:24:46.243 回答
0

GetFlags返回 an IEnumerable<T>,而不是 a List<T>,您不能在此处转换

但是,您应该能够从结果中构造一个列表:

List<Zone_Status_ZoneConditionFlagEnum> ZoneConditionFlags_List = flags.GetFlags().ToList();

However, the error does not match the code here exactly, it should complain about an IEnumerable not be able to be cast, but instead it says the enum type. Are you sure this is the right code?

于 2013-06-20T10:15:12.377 回答