从对象属性中删除Null

时间:2017-02-08 22:57:07

标签: c# object properties null

我正在寻找一种方法来设置' null'属性值为'非null'值。这些属性与一个对象相关联,并且有一个包含多个对象的列表。

我遇到的问题是转换' null'值为“非空”'每个属性具有不同类型的值。

到目前为止,我有一些嵌套循环和条件试图识别null属性并将它们设置为非null。

//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来回复制时并不好玩。

2 个答案:

答案 0 :(得分:0)

如果您正在寻找为任何引用类型生成默认非null值的方法,那么我担心您运气不好。语言中没有通用机制可以为任何给定的引用类型提供非null的默认值;默认值正好是null

如果您需要处理的类型集是有限且可管理的,那么您可能可能会对每个特定情况进行编码。

无论如何这看起来很奇怪。你想要完成什么?最有可能找到解决问题的方法。

答案 1 :(得分:0)

经过一段时间和研究后,避免此问题的最佳方法是为将在反序列化过程中创建的对象创建构造函数/默认值,然后使用此问题中描述的设置 - Why when I deserialize with JSON.NET ignores my default value?。将使用默认构造函数,并忽略空值。

objectsList = JsonConvert.DeserializeObject<List<RootObject>>(json_string, new JsonSerializerSettings
     {
                DefaultValueHandling = DefaultValueHandling.Populate,
                NullValueHandling = NullValueHandling.Ignore
      }

 );