Enum疯狂 [英] Enum Insanity

查看:93
本文介绍了Enum疯狂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求:

写一个bool验证方法" validate"接受(类型enum_a,类型enum_b)

Write a bool validation method "validate" that accepts (Type enum_a, Type enum_b)

当且仅当enum_b中的每个名称也存在于enum_a中并且enum_b中每个名称的int值具有相同的int值时才返回true enum_a中的相同命名项。

return true if and only if every name in enum_b also exists in enum_a and that the int value of each name in enum_b has the same int value for the same named item in enum_a.

这有点困难。

难以置信的是没有Enum.GetValue(enum_member_name)。我知道基础类型可以是int,long等,但这并不能证明这个功能不合理。

Incredibly there is no Enum.GetValue(enum_member_name). I know the underlying type can be int, long etc but this doesn't justify leaving this capability out.

任何人都有任何想法吗?

Anyone have any ideas?

Thx

PS - 几分钟后...

PS - A few mins later...

看起来我需要获取枚举类型的字段然后使用GetValue作为字段然后将该值转换为int - 似乎是唯一的方法 - fiddly代码一些如此基本的东西...

Looks like I need to get the enum type's Fields and then use GetValue for the field and then convert that value to an int - seems to be the only way - fiddly code for something so basic...

多了几分钟......

A few more mins...

这就是诀窍:

        internal static int GetEnumFieldValue (Type EnumType, string Name)
        {
            var field = EnumType.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.Name == Name).First();
            return Convert.ToInt32(field.GetValue(null));
        }

推荐答案

检查一下:

var names_a = Enum.GetNames( enum_a );
var names_b = Enum.GetNames( enum_b );

bool is_good_1 = names_b.All( nb => names_a.Contains( nb ) );
bool is_good_2 = names_b.All(
    nb =>
    {
        object va;
        try
        {
            va = Enum.Parse( enum_a, nb );
        }
        catch( ArgumentException )
        {
            return false;
        }
        object vb = Enum.Parse( enum_b, nb );

        return (int)va == (int)vb;
    } );


这篇关于Enum疯狂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆