C#反射枚举选项要常数值 [英] C# Reflection Enum Option To Constant Value

查看:292
本文介绍了C#反射枚举选项要常数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有反映枚举(DictionaryType)选项的Guid非常直接的方式代码

I have the code that reflects enum (DictionaryType) option to Guid in very straight-forward way

if (dictionaryType == DictionaryType.RegionType)
    return Consts.DictionaryTypeId.RegionType;

if (dictionaryType == DictionaryType.Nationality)
    return Consts.DictionaryTypeId.Nationality;

请,建议我反映枚举选项静态只读GUID值的最佳方式。

Please, suggest me the best way to reflect Enum option to static readonly guid value.

感谢您提前

编辑稍后:
我不能将任何属性枚举选项,'因为枚举是在数据模型大会宣布和枚举不应该与实现(的GUID,表...)

Edited a bit later: I can't assign any attributes to enumeration options, 'cos enumeration is declared in Data Model assembly and enumerations shouldn't be combined with implementation (Guids, Tables...)

推荐答案

在除了乔恩的回答,您可以提供的GUID作为一个单独的类,其中字段具有相同的名称作为其对应的枚举值的字段。

In addition to Jon's answer, you can provide the Guids as fields in a separate class, where the fields have the same name as their corresponding enum value.

这可以用来填充字典快速查找后:

This can be used to populate a dictionary for fast lookup later:

using System;
using System.Collections.Generic;

namespace SO2856896
{
    enum DictionaryType
    {
        RegionType,
        Nationality
    }

    class Consts
    {
        public class DictionaryTypeId
        {
            public static Guid RegionType = new Guid("21EC2020-3AEA-1069-A2DD-08002B30309D");
            public static Guid Nationality = new Guid("21EC2020-3AEA-1069-A2DD-08002B30309E");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<DictionaryType, Guid> table = new Dictionary<DictionaryType, Guid>();

            Type idType = typeof(Consts.DictionaryTypeId);
            foreach (DictionaryType dicType in Enum.GetValues(
                typeof(DictionaryType)))
            {
                System.Reflection.FieldInfo field = idType
                    .GetField(dicType.ToString(), 
                        System.Reflection.BindingFlags.Static
                        | System.Reflection.BindingFlags.Public);
                Guid guid = (Guid)field.GetValue(null);
                table[dicType] = guid;
            }

            foreach (DictionaryType dicType in Enum.GetValues(
                typeof(DictionaryType)))
            {
                Console.Out.WriteLine(dicType + ": " + table[dicType]);
            }
        }
    }
}

输出

RegionType: 21ec2020-3aea-1069-a2dd-08002b30309d
Nationality: 21ec2020-3aea-1069-a2dd-08002b30309e

我不完全知道我会选择我自己,但也许是乔恩的回答的组合,字典查找从的GUID和反射像上面来填充它。

I'm not entirely sure what I would chose myself, but perhaps a combination of Jon's answer, a dictionary to look up the guids from and reflection like above to populate it.

这篇关于C#反射枚举选项要常数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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