当为null时,将int强制转换为对象的int为0

时间:2019-02-28 09:48:36

标签: c# object properties non-nullable

抱歉,我想不出更好的标题来描述这个问题。

我使用以下代码使更新配置属性的特定值更加容易。请注意,配置属性不仅是整数,而且不仅仅是2个整数,在此示例中只是对其进行了简化。

public class Config {
    public int VarA { get; set; }
    public int VarB { get; set; }
}
private Config config;
private void Update(Config newValues) {
    PropertyInfo[] properties = typeof(Config).GetProperties();
    foreach (PropertyInfo property in properties) {
        object n = property.GetValue(newValues);
        property.SetValue(config, n ?? property.GetValue(config));
    }
}

Update方法检查newValues的属性,如果定义了值,将更新config的属性。

我使用类似的值初始化配置(仅作为示例):

config = new Config() { VarA = 1, VarB = 2 };
Debug.WriteLine(config.VarA + " : " + config.VarB); // 1 : 2

然后,如果我只想将VarA更新为0且不触摸VarB,请执行以下操作:

Update(new Config() { VarA = 0 });
Debug.WriteLine(config.VarA + " : " + config.VarB); // 0 : 0

但是这会导致VarB也被设置为0,因为newValues没有为其分配值,而null值是int为0,因为int是不可为空的。在newValues中未定义VarB时,如何使VarB保持值为2?

2 个答案:

答案 0 :(得分:1)

感谢乔恩·斯凯特(Jon Skeet),我不知道您可以使值类型为可空的,因此可以进行以下工作:

public class Config {
    public int? VarA { get; set; }
    public int? VarB { get; set; }
}

我知道其他答案在某些情况下也可以使用,但是我正在从不同的json文件填充这些配置属性,并且有许多属性,因此我不想手动将它们全部键入。

答案 1 :(得分:0)

在您的(Config newValues)参数的更新过程中,请提供现有的已修改Config参数,而不是创建新的配置对象。

创建新的Config对象会重置所有现有值。

config = new Config() { VarA = 1, VarB = 2 }; 
Debug.WriteLine(config.VarA + " : " + config.VarB);

config.VarA = 0;
Update(config);
Debug.WriteLine(config.VarA + " : " + config.VarB);
相关问题