首页 > 解决方案 > C#设置原始类型的泛型属性值

问题描述

我正在尝试在 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);
    }
}

问题是我不能propertyType用作获取默认值的类型。我如何获得propertyType可以使用的类型default()

标签: c#genericsreflection

解决方案


您应该将实例传递给 SetValue:

prop.SetValue(valueObject, value);

如果要设置默认值,可以使用:

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

推荐阅读