[英]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# 我正在尝试在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. 问题是我无法使用
propertyType
作为类型来获取其默认值。 How do I get propertyType
to a type that can be used by default()
? 如何将
propertyType
设置为default()
可以使用的类型?
You should pass the instance to the SetValue: 您应该将实例传递给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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.