如何防止默认参数覆盖分配的值?

时间:2019-06-05 01:16:01

标签: c# methods parameter-passing

这是我的代码:一种更改PC部件的方法。

internal void ModifyPC(double CPU_Clockspeed = 0, int RAM = 0, int storage = 0, int graphicsMemory = 0)
{
    this.CPU_Clockspeed = CPU_Clockspeed;
    this.RAM_capacity = RAM;
    this.storage = storage;
    this.graphicsCardCapacity = graphicsMemory;
}

如何仅更改单个变量值,而不覆盖默认值?

例如,我创建了具有4.0 GHz CPU,16GB RAM,250GB存储和8GB图形卡的PC。 Desktop PC = new Desktop(4.0, 16, 250, 8);

例如,如果我尝试将CPU更改为4.5 Ghz:PC.ModifyPC(CPU_Clockspeed: 4.5);,则会将所有其他属性覆盖为0。

2 个答案:

答案 0 :(得分:3)

默认全部为Nullable<>,并且仅在不为空时分配一个值

internal void ModifyPC(
    double? CPU_Clockspeed = null, int? RAM = null, int? storage = null, int? graphicsMemory = null)
{
    this.CPU_Clockspeed = CPU_Clockspeed.GetValueOrDefault(this.CPU_Clockspeed);
    this.RAM_capacity = RAM.GetValueOrDefault(this.RAM_capacity);
    this.storage = storage.GetValueOrDefault(this.storage);
    this.graphicsCardCapacity = graphicsMemory.GetValueOrDefault(this.graphicsCardCapacit);
}

现在仅设置具有传递值的参数

答案 1 :(得分:1)

由于任何一个参数都不能具有负值,因此从理论上讲,您可以使用-1而不是null。然后,您可以将以下逻辑应用于函数。

internal void ModifyPC(double CPU_Clockspeed = -1, int RAM = -1, int storage = -1, int graphicsMemory = -1)
{
   if (CPU_Clockspeed != -1) this.CPU_Clockspeed = CPU_Clockspeed;
   if (RAM != -1) this.RAM_capacity = RAM;
   if (storage != -1) this.storage = storage;
   if (graphicsMemory != -1) this.graphicsCardCapacity = graphicsMemory;
}