从propertyType中提取枚举类型

Rag*_*pur 0 c# generics enums

我有以下情况

public class TestData
{
     public TestEnum EnumTestData{get;set;}
}

public Enum TestEnum
{
     Test1,Test2,Test3 
}
Run Code Online (Sandbox Code Playgroud)

我还有另一个类遍历我的TestData类的所有属性。根据属性类型,它将为其生成随机数据。现在,当我的propertyType是Enum类型时,如何知道它是哪种枚举以及如何获取Test1,Test2或Test3作为输出?

p.s*_*w.g 5

您可以使用Type.GetProperties方法获取所有属性的列表:

var targetType = typeof(TestData);
var properties = targetType.GetProperties();
Run Code Online (Sandbox Code Playgroud)

然后Enum通过检查PropertyInfo.PropertyTypeand Type.IsEnum属性来检查它是否为类型:

foreach(var prop in properties)
{
    if (prop.PropertyType.IsEnum)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

最后使用以下Enum.GetValues方法获得随机值:

var random = new Random();
...

var values = Enum.GetValues(prop.PropertyType);
var randomValue = ((IList)values)[random.Next(values.Length)];
Run Code Online (Sandbox Code Playgroud)