C# 如何循环任何枚举以将所有可能的值转换为字符串?
正如标题所述,从该枚举中:C# 如何循环任何枚举以将所有可能的值转换为字符串?,c#,string,list,methods,enums,C#,String,List,Methods,Enums,正如标题所述,从该枚举中: public enum DeeMacsEnum { Value1, Value2, Value3 } 我想要一份列表。第一个元素将有“Value1”,第二个元素将有“Value2”等 但是,我希望保持此方法的通用性,使其能够遍历任何类型的枚举 我所尝试的: Array values = Enum.GetValues(typeof(DeeMacsEnum)); ^这个很好用。但不是通用的。为了使其可重复使用,我将其更改为: var type = enumObject
public enum DeeMacsEnum
{
Value1,
Value2,
Value3
}
我想要一份列表
。第一个元素将有“Value1”,第二个元素将有“Value2”等
但是,我希望保持此方法的通用性,使其能够遍历任何类型的枚举
我所尝试的:
Array values = Enum.GetValues(typeof(DeeMacsEnum));
^这个很好用。但不是通用的。为了使其可重复使用,我将其更改为:
var type = enumObject.GetType();
Array values = Enum.GetValues(typeof(type));
不起作用(甚至不编译),这是可以理解的。试试:
var names = Enum.GetNames(typeof(DeeMacsEnum));
尝试:
实际上您有
type
,不再需要使用typeof
var type = enumObject.GetType();
Array values = Enum.GetValues(type);
实际上您有
type
,不再需要使用typeof
var type = enumObject.GetType();
Array values = Enum.GetValues(type);
您可以使用以下选项:
string[] s = Enum.GetNames(typeof(YourEnumType));
您可以使用以下选项:
string[] s = Enum.GetNames(typeof(YourEnumType));
为什么不试试这个
public IEnumerable<string> getEnumValues<T>() where T: struct,IConvertible
{
var type = typeof(T);
if (type.IsEnum)
{
return Enum.GetNames(type);
}
else
{
throw new ArgumentException("Type parameter specified is not an enum type.");
}
}
public IEnumerable getEnumValues(),其中T:struct,IConvertible
{
var类型=类型(T);
if(type.IsEnum)
{
返回Enum.GetNames(类型);
}
其他的
{
抛出新ArgumentException(“指定的类型参数不是枚举类型”);
}
}
为什么不试试这个
public IEnumerable<string> getEnumValues<T>() where T: struct,IConvertible
{
var type = typeof(T);
if (type.IsEnum)
{
return Enum.GetNames(type);
}
else
{
throw new ArgumentException("Type parameter specified is not an enum type.");
}
}
public IEnumerable getEnumValues(),其中T:struct,IConvertible
{
var类型=类型(T);
if(type.IsEnum)
{
返回Enum.GetNames(类型);
}
其他的
{
抛出新ArgumentException(“指定的类型参数不是枚举类型”);
}
}
问题就在这里。试试这个。数组值=Enum.GetValues(类型);问题就在这里。试试这个。数组值=Enum.GetValues(类型);当然,我已经有这种类型了。我现在觉得很可笑。这么简单。非常感谢。当然我已经有了这个型号。我现在觉得很可笑。这么简单。非常感谢。