简体   繁体   English

从propertyType中提取枚举类型

[英]Extracting enum type from propertyType

I have the below scenario 我有以下情况

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

public Enum TestEnum
{
     Test1,Test2,Test3 
}

I have another class which traverse through my TestData class for all properties. 我还有另一个类遍历我的TestData类的所有属性。 Depending on the property type it will generate random data for it. 根据属性类型,它将为其生成随机数据。 Now when my propertyType is Enum type, How can I know which type of enum it is and how to get either Test1, Test2 or Test3 as my output? 现在,当我的propertyType是Enum类型时,如何知道它是哪种枚举以及如何获取Test1,Test2或Test3作为输出?

You can get a list of all properties using the Type.GetProperties method: 您可以使用Type.GetProperties方法获取所有属性的列表:

var targetType = typeof(TestData);
var properties = targetType.GetProperties();

Then check whether it's an Enum type by checking the PropertyInfo.PropertyType and Type.IsEnum properties: 然后通过检查PropertyInfo.PropertyTypeType.IsEnum属性来检查它是否为Enum类型:

foreach(var prop in properties)
{
    if (prop.PropertyType.IsEnum)
    {
        ...
    }
}

Finally get a random value using the Enum.GetValues method: 最后使用Enum.GetValues方法获得一个随机值:

var random = new Random();
...

var values = Enum.GetValues(prop.PropertyType);
var randomValue = ((IList)values)[random.Next(values.Length)];

You can just .ToString() the EnumTestData property, like this: 您可以仅.ToString() EnumTestData属性,如下所示:

var test = new TestData();
test.EnumTestData = TestEnum.Test1;

var dummy = test.EnumTestData.ToString();

Note: dummy will be "Test1" . 注意: dummy将是"Test1"

Not entirely sure what you're asking, but this is how you would compare and get the string value of an enum: 不能完全确定您要问的是什么,但这是您进行比较并获取枚举的字符串值的方式:

var td = new TestData();
// compare
if (td.EnumTestData == TestEnum.Test1)
{
    // Will output "Test1"
    Console.WriteLine(td.EnumTestData.ToString());
}

Also, I'm sure it's just a typo but it's enum not Enum : 另外,我敢肯定,这只是一个错字,但它enumEnum

public enum TestEnum
{
     Test1,Test2,Test3 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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