我有几个求职信:
public class ClassA
{
public enum A {a, b, c, d};
public class ClassB
{
public enum B {b1, b2, b3, b4};
public enum C {c1, c2, c3};
}
// ...
}现在,我需要使用枚举执行一些操作,例如:
A.a应显示为用户的“条件A”,B.b1应显示为“选项1")我的问题是组织这些方法。
有很多枚举,我需要将方法链接到其中一些
问:在我的应用程序中,我把操作不同枚举的方法存储在哪里?
我应该为每个枚举创建一个类吗?还是使用自定义类来操作所有枚举和名称方法?
Enum不是一个类,它不能容纳静态方法,理想情况下,我希望它们在里面。这将非常方便,只要我能够输入A.,智能就会提供给我:
a, b, c, d, A[] FilterValues(bool condition), string[] AllValuesTranslated(), string TranslateMembmer(A member)
我希望问题是清楚的(不知道如何解释我需要更短的时间,抱歉)。
发布于 2013-10-25 13:23:12
下面是一些实用程序扩展方法,可以帮助:~
用法:
var listOfValues = typeof (A).ToList();
var listOfKeyValuePairs = typeof(A).ToListOfKeyValuePair();
var dictionaryOfValues = typeof(A).ToDictionary();鉴于以下原因:
public enum A
{
[EnumValueDescription("This is a")] a = 1,
[EnumValueDescription("This is b")] b = 2,
[EnumValueDescription("This is c")] c = 3,
[EnumValueDescription("This is d")] d = 4
};以及以下自定义属性:
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = false)]
public class EnumValueDescriptionAttribute : Attribute
{
public string StringValue
{
get;
protected set;
}
public EnumValueDescriptionAttribute(string value)
{
this.StringValue = value;
}
}以及以下扩展方法:
public static class EnumExtentions
{
public static List<Enum> ToList(this Type type)
{
return Enum.GetValues(type)
.OfType<Enum>()
.ToList();
}
public static Dictionary<int, string> ToDictionary(this Type type)
{
return type.GetEnumValues().Cast<Enum>().ToDictionary(Convert.ToInt32, e => e.GetDescription());
}
public static List<KeyValuePair<int, string>> ToListOfKeyValuePair(this Type type)
{
return Enum.GetValues(type)
.OfType<Enum>()
.Select(e => new KeyValuePair<int, string>(Convert.ToInt32(e), e.GetDescription()))
.ToList();
}
public static string GetDescription(this Enum value)
{
return value.GetDescription(null);
}
public static string GetDescription(this Enum value, string defaultValue)
{
var allFields = value.GetType().GetFields();
if (!allFields.Any())
return defaultValue;
var targetField = allFields.FirstOrDefault(fi => (fi.IsLiteral && (fi.GetValue(null).Equals(value))));
if (targetField == null)
return defaultValue;
var attrib = targetField.GetCustomAttributes(typeof(EnumValueDescriptionAttribute), false)
.OfType<EnumValueDescriptionAttribute>()
.FirstOrDefault();
return attrib == null ? defaultValue : attrib.StringValue;
}
}还不完全清楚您需要哪些其他操作方法。
https://stackoverflow.com/questions/19590191
复制相似问题