C# Reflection Enum Option To Constant Value

2019-06-04 02:20发布

问题:

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;

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

Thank you in advance

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...)

回答1:

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]);
            }
        }
    }
}

Outputs:

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

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.



回答2:

A couple of simple options:

  • A switch statement
  • A Dictionary<DictionaryType, Guid> (which could be populated by reflection if you really wanted)


标签: c# reflection