简体   繁体   English

其中Lambda中的Condition具有两个值

[英]Where Condition in Lambda with two values

public enum Values
{
    [Description("All Fabs")]
    value1 = 0,
    [Description("Fab 1")]
    value2 = 1,
    [Description("Fab 2")]
    value3 = 2,
    [Description("Fab 3")]
    value4 = 3,
    [Description("Fab 4")]
    value5 = 4,
    [Description("Fab 5")]
    value6 = 5           
}

public static Dictionary<int, string> ConvertEnumToDictionary<T>()
{
    var type = typeof(T);
    if(!type.IsEnum)
    {
        throw new InvalidOperationException();
    }
    Dictionary<int, string> result = new Dictionary<int, string>();
    bool header = true;
    foreach(var field in type.GetFields())
    {
        if(header)
        {
            header = false;
            continue;
        }
        var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
        if(attribute != null)
        {
            result.Add((int)field.GetValue(null), attribute.Description);
        }
    }
    return result;
}

Displays.ConvertEnumToDictionary<Values>().Where(i => (i.Key == value2 || i.Key == value1));

the above line produces diff results in development environment and in staging environment. 上面的代码在开发环境和登台环境中产生差异结果。

In development it returns both the values but in staging sometimes it returns one value only (either value1 or value2 ) and sometimes both. 在开发中,它返回两个值,但在暂存中,有时仅返回一个值( value1value2 ),有时返回两个值。

Please help me find out the problem here. 请帮助我在这里找出问题所在。

It may be because of this sentence in the documentation : 可能是由于文档中的这一句话:

Your code must not depend on the order in which fields are returned, because that order varies. 您的代码不得依赖于字段返回的顺序,因为该顺序会有所不同。

You're skipping the first item you iterate (your header variable). 您正在跳过要迭代的第一项( header变量)。 That will only work if the fields come back in the same order every time. 仅在每次字段以相同顺序返回时,这才起作用。

Try removing the code that skips the "header", and instead getting the field value into a variable and checking whether value.Equals(default(T)) . 尝试删除跳过“标头”的代码,而是将字段值放入变量中,并检查value.Equals(default(T)) That would skip the enum value with 0 as its backing integer value. 这将跳过枚举值,并将其作为整数0作为其后备整数值。

It may be linked to the "header" part while iterating raw fields. 在迭代原始字段时,它可以链接到“标头”部分。 Prefer this manner to iterate thru enum values: 最好以这种方式迭代枚举值:

FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static)

Then you can start at offset-0: 然后,您可以从offset-0开始:

for (int i = 0; i < fields.Length; i++)

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

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