使用Convert.ChangeType转换为属性的类型

时间:2013-12-04 23:08:27

标签: c# .net object properties casting

我需要遍历对象的属性并获取每个基本属性(和字符串)的值。我已经有代码来处理索引器,复杂对象和可以为空的原语,所以不要担心这些(我从代码中排除了那些以保持简单)。我遇到的问题是当我使用Convert.ChangeType()时。变量“value”始终为System.Object类型。如何将其转换为字符串或int,如“SomeObject”对象中所示?

SomeObject someObject = new SomeObject();

foreach (PropertyInfo propertyInfo in someObject.GetType().GetProperties())
{
    Type propertyType = propertyInfo.PropertyType;

    // How can I cast this to the type of "propertyType"?
    var value = Convert.ChangeType(propertyInfo.GetValue(someObject, null), propertyType);
}

public class SomeObject
{
    public string SomeString { get; set; }
    public int SomeInt { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您可以执行类似

的操作
if (propertyType == typeof(int))
{
    var value = (int)Convert.ChangeType(propertyInfo.GetValue(testo, null), propertyType);
}
else if(propertyType == typeof(string))
{
    var value = (string)Convert.ChangeType(propertyInfo.GetValue(testo, null), propertyType);
}