I have the enum:
public enum Colors { Yellow, Red }
Then I have a string:
String enumName = "Colors";
Is it possible to get an enum instance from the enumName? Something like:
Enum colors = // get enum with name "Colors".
Thank You, Miguel
are you looking for something like this?
using System;
using System.Linq;
namespace Stuff
{
class Program
{
static void Main(string[] args)
{
string enumName = "Colors";
string value = "Red";
var loadedPublicTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetExportedTypes());
var possibleEnums = loadedPublicTypes.Where(x => x.IsEnum && x.Name == enumName);
foreach (var e in possibleEnums)
{
Console.WriteLine("{0} is{1} a member of {2}", value, Enum.GetNames(e).Contains(value) ? "" : " not", e.FullName);
}
}
}
public enum Colors
{
Red,
Yellow
}
}
You could use a dynamic type and find a variable by name, but you would have to have an instance of all the enums you want to include in your search.
Check out the following post: Getting variable by name in C# .
You need the full name of the enumeration type (eg System.Drawing.KnownColor, System.Drawing
, or Microsoft.MediaCenter.UI.Colors, Microsoft.MediaCenter.UI
).
Once you have this, you can use reflection to create an instance of the corresponding enum.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.