[英]c# generic Enum class operations
我正在尝试实现以下目标:拥有一个将获取通用Enum并检查该Enum是否来自同一类中定义的Enum的方法,以及拥有另一个返回已成功检查Enum的int值的方法。
这是一个例子:
public class MyClass(){
public enum MyValue{
Value1,
Value2,
Value3,
}
public enum MyString{
String1,
String2,
String3,
}
public void Usage(Enum something){
if(IsRight(typeof(MyValue))){
Console.WriteLine("something = " + GetInt(something));
} else {
Console.WriteLine("ERROR: something is not MyValue");
}
if(IsRight(typeof(MyString))){
Console.WriteLine("something = " + GetInt(something));
} else {
Console.WriteLine("ERROR: something is not MyString");
}
}
private bool IsRight(System.Type enumType){
// THIS IS WRONG and I don't know how to do it...
return enumType.IsAssignableFrom(MyClass);
}
private int GetInt(Enum enumeration){
// is there a better way to do the int conversion?
return (int)Convert.ChangeType(enumeration, typeof(int));
}
}
实际上,GetInt方法有效,但是我想知道是否有更简单的方法可以做到这一点。 关于IsRight方法,我不知道该怎么做。 基本上,问题是我需要检查传递的枚举值是否属于同一类中定义的任何枚举,该方法是避免用户将类不知道的枚举传递给我。
非常感谢你 :-)
编辑我很抱歉,因为这个例子可能不是很好。 我知道我可以使用is关键字列出所有Enum,但是由于我在类中定义了许多Enum,因此该函数的一个更好的例子是:
public class MyClass(){
public enum MyValue{
Value1,
Value2,
Value3,
}
public enum MyString{
String1,
String2,
String3,
}
private List<string> m_cachedStrings = new List<string>();
public void Usage(Enum something){
CacheStrings(typeof(MyValue));
CacheStrings(typeof(MyString));
}
private bool CacheStrings(System.Type enumType){
// THIS IS WRONG and I don't know how to do it...
if(!enumType.IsAssignableFrom(MyClass))
return;
foreach(var item in Enum.GetValues(enumType)){
m_cachedStrings.Add(item.ToString());
}
}
}
尝试这个:
private bool IsRight(System.Type enumType){
return enumType.DeclaringType == typeof(MyClass);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.