假设我有这个枚举:
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
}
}
我在一个字符串变量中有它的名字,比如:
string EnumAtt = "SalaryCriteria";
我正在尝试检查这个枚举是否由这个名称定义,如果定义了我想获取它的实例。我已经尝试过这样,但是 type
返回 null
:
string EnumAtt = "SalaryCriteria";
Type myType1 = Type.GetType(EnumAtt);
我也试过这个:
string EnumAtt = "BusinessRule.SalaryCriteria";
Type myType1 = Type.GetType(EnumAtt);
知道如何实现这一目标。
最佳答案
要在当前 AppDomain 中搜索所有加载的程序集以获得给定的枚举——没有完全限定的程序集名称——你可以这样做:
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;
}
例如(选择一个不在我的程序集中的 semi-random enum):
var type1 = Type.GetType("System.Xml.Linq.LoadOptions") // Returns null.
var type2 = GetEnumType("System.Xml.Linq.LoadOptions") // Returns successfully.
您的名称仍应包含命名空间。
关于c# - 如何通过在字符串中指定其名称来获取枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25404237/