简体   繁体   中英

Casting To A Property's Type Using Convert.ChangeType

I need to iterate through the properties of an object and obtain the values of each primitive property (and strings). I already have code in place to deal with indexers, complex objects and nullable primitives, so don't worry about those (I excluded those from the code to keep it simple). The problem I'm running into is when I use Convert.ChangeType(). The variable "value" is always of type System.Object. How can I convert it to a string or int as shown in the "SomeObject" object?

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

You can do something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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