【发布时间】:2017-06-26 18:50:55
【问题描述】:
我正在寻找一种将“空”属性值设置为“非空”值的方法。这些属性与一个对象相关联,并且存在多个对象的列表。
我遇到的问题是将“空”值转换为“非空”值,其中每个属性都有不同的类型。
到目前为止,我有一些嵌套循环和条件,试图识别空属性并将它们设置为非空。
//loop through each object
for (int i = 0; i < objectList.Count; i++)
{
//loop through each object and each field within that object
foreach (var property in objectList[i].GetType().GetProperties())
{
var current_field_val = property.GetValue(objectList[i], null);
//null validation
if (current_field_val == null)
{
PropertyInfo current_field_data_type = objectList[i].GetType().GetProperty(property.Name);
if (current_field_data_type is String)
{
objectList[i].GetType().GetProperty(property.Name).SetValue(objectList[i], "");
}
else if (current_field_data_type is int)
{
objectList[i].GetType().GetProperty(property.Name).SetValue(objectList[i], 0);
}
else if (current_field_data_type is double)
{
objectList[i].GetType().GetProperty(property.Name).SetValue(objectList[i], 1);
}
else if (current_field_data_type is object)
{
objectList[i].GetType().GetProperty(property.Name).SetValue(objectList[i], "");
}
}
}
}
对不起,我的缩进很差,VS在来回复制时玩得不好。
【问题讨论】:
-
感谢@Damian 的清理编辑!
-
你的问题到底是什么?什么没有按预期工作?
-
顺便说一句,这似乎是一个非常糟糕的主意。整数和双精度也不能为空,除非它们被设为可为空的整数和双精度。从根本上说,您在设计的早期就出错了,这是尝试清理它的讨厌黑客
-
由于我的 JSON 映射到我的对象的方式,只要有一个空白字段 - 就会使用 null(这是预期的)。现在,我希望用适合属性数据类型的值替换所有空值(防止转换错误)但是,我似乎无法找到一种有效的方法来 1. 检查特定的数据类型和 2. 设置值没有转换错误。
-
那你为什么不在你的json反序列化中处理这个呢?
标签: c# object properties null