c# - 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()
?
解决方案
您应该将实例传递给 SetValue:
prop.SetValue(valueObject, value);
如果要设置默认值,可以使用:
var propertyType = prop.PropertyType;
var defaultValue = Activator.CreateInstance(propertyType);
prop.SetValue(valueObject, defaultValue);
推荐阅读
- html - 是否所有浏览器都会忽略 html 中的空行
- php - PHP foreach if isset
- c# - ASP.NET MVC 中的自定义路由绕过主控制器/索引
- jquery - 我想在jquery中获取数据
- jenkins - 将 groovy 字符串变量传递给 jenkins 作业 dsl 授权
- azure - Azure 中并行查询的 CosmosDB SocketException
- reactjs - 如何从反应中获取数据?
- html - 如何通过将鼠标悬停在其中一个上来将两个元素设置为不同的样式?没有 JavaScript
- java - JAVA JRE 的升级 - 操作系统级别的系统上
- python - 训练 Keras 模型被两个 ImageDataGenerators 卡住