简体   繁体   中英

converting value types of an object to Dictionary<string, string>

How do I iterate through all the value types of an object and convert that into a Dictionary? I was heading the reflection way

obj.GetType().GetProperties()

but that gives both value types and references types.

You can just use the IsValueType property of the PropertyInfo Type :

obj.GetType().GetProperties().Where(x => x.PropertyType.IsValueType)

Adding it to a dictionary becomes:

foreach (var propertyInfo in obj.GetType().GetProperties().Where(x => x.PropertyType.IsValueType)) {
    dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(obj));
}

Where the key is the name and the value is the value in the obj instance.

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