【发布时间】:2013-12-21 16:29:16
【问题描述】:
我需要遍历对象的属性并获取每个原始属性(和字符串)的值。我已经有了处理索引器、复杂对象和可为空的原语的代码,所以不用担心这些(我从代码中排除了这些以保持简单)。我遇到的问题是当我使用 Convert.ChangeType() 时。变量“值”始终是 System.Object 类型。如何将其转换为“SomeObject”对象中所示的字符串或 int?
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; }
}
【问题讨论】:
标签: c# .net object properties casting