How to get enum Type by specifying its name in String

天涯浪子 提交于 2020-06-08 07:53:25

问题


Suppose i have this Enum:

namespace BusinessRule
{
    public enum SalaryCriteria : int
        {
            [EnumDisplayName(DisplayName = "Per Month")]
            Per_Month = 1,
            [EnumDisplayName(DisplayName = "Per Year")]
            Per_Year = 2,
            [EnumDisplayName(DisplayName = "Per Week")]
            Per_Week = 3
        }
}

I have its name in a string variable like :

string EnumAtt = "SalaryCriteria";

i am trying to check if this Enum is defined by this name, and if defined i want to get its instance.i have tried like this, but type is returning null:

string EnumAtt = "SalaryCriteria";
Type myType1 = Type.GetType(EnumAtt);

i have also tried this:

string EnumAtt = "BusinessRule.SalaryCriteria";
Type myType1 = Type.GetType(EnumAtt);

any idea how i can achieve this.


回答1:


To search all loaded assemblies in the current AppDomain for a given enum -- without having the fully qualified assembly name -- you can do:

    public static Type GetEnumType(string enumName)
    {
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            var type = assembly.GetType(enumName);
            if (type == null)
                continue;
            if (type.IsEnum)
                return type;
        }
        return null;
    }

For instance (picking a semi-random enum which is not in my assembly):

var type1 = Type.GetType("System.Xml.Linq.LoadOptions") // Returns null.
var type2 = GetEnumType("System.Xml.Linq.LoadOptions") // Returns successfully.

You name should still include the namespace.




回答2:


A LINQ-inspired answer:

public static Type GetEnumType(string name)
{
  return 
   (from assembly in AppDomain.CurrentDomain.GetAssemblies()
    let type = assembly.GetType(name)
    where type != null
       && type.IsEnum
    select type).FirstOrDefault();
}

The reason is that you need to go through all loaded assemblies, not only the current assembly.




回答3:


This works great for me.

Type myType1 = Type.GetType("BusinessRule.SalaryCriteria");

enter image description here

I tried it without "EnumDisplayName" attribute.




回答4:


This works well:

using System;

namespace BusinessRule
{
  public enum SalaryCriteria : int
  {
    Per_Month = 1,

    Per_Year = 2,

    Per_Week = 3
  }
}

namespace ConsoleApplication16
{
  internal class Program
  {
    private static void Main()
    {
      string EnumAtt = "BusinessRule.SalaryCriteria";
      Type myType1 = Type.GetType(EnumAtt);

      Console.WriteLine(myType1.AssemblyQualifiedName);
      Console.ReadLine();
    }
  }
}


来源:https://stackoverflow.com/questions/25404237/how-to-get-enum-type-by-specifying-its-name-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!