C# 如何防止默认参数覆盖指定的值?

C# 如何防止默认参数覆盖指定的值?,c#,methods,parameter-passing,C#,Methods,Parameter Passing,这是我的代码:一种改变电脑部件的方法 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.graphicsCardCapac

这是我的代码:一种改变电脑部件的方法

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.0GHz CPU、16GB RAM、250GB存储和8GB图形硬盘的PC。台式电脑=新桌面4.0,16250,8


例如,如果我尝试将CPU更改为4.5 Ghz:PC.ModifyPCCPPU_时钟速度:4.5;,这将覆盖所有其他属性为0。

因为这些参数中的任何一个都不能为负值,所以理论上,可以使用-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;
}

由于这些参数中的任何一个都不能为负值,因此理论上可以使用-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;
}
默认“全部”为Nullable,并且仅在不为null时分配一个值

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);
}
现在,只有传递了值的参数才会被设置为默认值all为Nullable,并且只有在不为null时才赋值

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);
}

现在只有传递值的参数将被设置

然后您需要将all默认为nullable,如果不为null,则只分配一个值。然后您需要将all默认为nullable,如果不为null,则只分配一个值。Int32.MinValue比-1更安全,但代价是更详细。是,我更喜欢它,因为那时一切都是常数。这似乎比所有空值的公认答案更清晰。Int32.MinValue比-1更安全,但代价是更详细。是的,我确实比-1更喜欢它,因为这样一切都是常量。这似乎比所有空值的公认答案更清晰。