简体   繁体   中英

c# check if a class has defined enum

I have a class like this

public class SomeClass {
public enum Status { A,B,C}
}

I want to do

bool enumExists = MysteryMethod("SomeClass.Status");

What goes inside MysteryMethod ?

Enums are types themselves.

Nested types are named with + between the container class and the type name

Therefore, the name of the mystery method would be Type.GetType

public class SomeClass
{
    public enum Status
    {

    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Type t = Type.GetType("Lab.SomeClass+Status", false);
        bool isEnum = t.IsEnum;
    }
}

Figured it out:

var asm = System.Reflection.Assembly.GetExecutingAssembly(); 
var typ = asm.GetType("SomeClass+Status")
var enumExists = (typ != null && typ.IsEnum);

Trick is to put + after class name when you GetType.

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