简体   繁体   中英

using typeof to find and Enum class by its name in c#

I'm looking for a way to implement such code:

public enum Enum1
{
    a=0,b
}

string enumName="Enum1";

Enum[] myEnum = (Enum[])Enum.GetValues(typeof(enumName));

I want to get a set of enums by their name; but the "typeof" part won't work. please help.

typeof is a compile-time operator that would obviously work only for types that are known at compile-time.

If you need to load a certain type using a string , you can use the Type.GetType() method instead:

Enum[] myEnum = (Enum[])Enum.GetValues(Type.GetType(enumName));

Keep in mind, though, that you'll typically require the full namespace, not just the class name. For example: "MyNamespace.Enums.Enum1" .

See MSDN

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.

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