简体   繁体   English

C#枚举/反射

[英]C# enums/reflection

Let's say I have a function that takes a string. 假设我有一个采用字符串的函数。 That string contains the fully name of an enum type (eg "MyCompany.Area.AotherNamespace.MyEnum"). 该字符串包含枚举类型的全名(例如“ MyCompany.Area.AotherNamespace.MyEnum”)。

How could I create an array of strings (or List<string> ) whose elements are the values of MyCompany.Area.AotherNamespace.MyEnum ? 我如何创建一个字符串数组(或List<string> ),其元素是MyCompany.Area.AotherNamespace.MyEnum的值?

Is that even possible? 那有可能吗?

I'm basically trying to serialize an enum type serverside and then output it in clientside JavaScript so I don't have to define an enum in two places--in my C# and my JavaScript. 我基本上是想序列化枚举类型的服务器端,然后在客户端JavaScript中输出它,因此我不必在两个地方(在C#和JavaScript中)定义枚举。

Type type = Type.GetType(yourStringWithTheFullEnumName);
string[] valueNames = Enum.GetNames(type);

This doesn't work in Silverlight (and possibly the Compact Framework). 这在Silverlight(可能还有Compact Framework)中不起作用。 If you are working in an "alternative" CLR, then you can get the same effect with a tad bit of reflection. 如果您使用的是“替代” CLR,则可以通过一点反射来获得相同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM