简体   繁体   中英

C# Set generic property value of primitive type

I am trying to set the value of a primitive type in an generic object dynamically in C#

//Create a new instance of the value object (VO)
var valueObject = Activator.CreateInstance<T>();
//Get the properties of the VO
var props = valueObject.GetType().GetProperties();
//Loop through each property of the VO
foreach (var prop in props)
{
    if (prop.GetType().IsPrimitive)
    {
         var propertyType = prop.PropertyType;
         var value = default(propertyType);
         prop.SetValue(prop, value);
    }
}

The problem being that I cannot use propertyType as a type to get the default value for. How do I get propertyType to a type that can be used by default() ?

You should pass the instance to the SetValue:

prop.SetValue(valueObject, value);

If you want to set the default value, you could use:

var propertyType = prop.PropertyType;
var defaultValue = Activator.CreateInstance(propertyType);
prop.SetValue(valueObject, defaultValue);

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