c#中获得某个枚举的所有名称
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system;
using system.collections.generic;
public static class enumhelper
{
public static list<string> askenumnames<t>() where t : enum
{
type enumtype = typeof(t);
list<string> enumnames = new list<string>();
foreach (string name in enum.getnames(enumtype))
{
enumnames.add(name);
}
return enumnames;
}
}
// 使用示例
public enum colors
{
red,
green,
blue
}
class program
{
static void main(string[] args)
{
list<string> enumnames = enumhelper.askenumnames<colors>();
foreach (string name in enumnames)
{
console.writeline(name);
}
}
}输出结果如下:

用以上方法即可正常获取某个枚举的所有名称。
下面附件一个c#的反射的典型例子:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.reflection;
namespace reflectionexample
{
class program
{
static void main(string[] args)
{
// 通过反射创建类型的实例
type mytype = typeof(myclass);
object myinstance = activator.createinstance(mytype, new object[] { "hello" });
// 获取并调用类型的方法
methodinfo mymethod = mytype.getmethod("mymethod");
mymethod.invoke(myinstance, new object[] { "world" });
}
}
class myclass
{
public myclass(string message)
{
console.writeline(message);
}
public void mymethod(string message)
{
console.writeline(message);
}
}
}运行结果:

这个例子,利用反射机制构造了对象,并且调用了成员函数。
到此这篇关于c#实现获得某个枚举的所有名称的文章就介绍到这了,更多相关c#获得枚举所有名称内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论