繁体   English   中英

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

[英]Casting To A Property's Type Using Convert.ChangeType

我需要遍历对象的属性并获取每个原始属性(和字符串)的值。 我已经有适当的代码来处理索引器,复杂的对象和可为空的基元,因此不必担心这些(为了简化起见,我从代码中排除了它们)。 我遇到的问题是当我使用Convert.ChangeType()时。 变量“值”始终为System.Object类型。 如何将其转换为“ 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; }
}

你可以做类似的事情

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);
}

暂无
暂无

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

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