我有以下情况
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作为输出?
您可以使用Type.GetProperties
方法获取所有属性的列表:
var targetType = typeof(TestData);
var properties = targetType.GetProperties();
Run Code Online (Sandbox Code Playgroud)
然后Enum
通过检查PropertyInfo.PropertyType
and 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)
归档时间: |
|
查看次数: |
559 次 |
最近记录: |