[英]Use default value with C# method overload
What is the best way to achieve this: I have a class with 2 method overloads which I create n object from.实现这一目标的最佳方法是什么:我有一个 class 和 2 个方法重载,我从中创建了 n object。 If I define b it will used and if not the default.
如果我定义 b 它将使用,如果不是默认值。 Where/How do I use this default without changing it permanently in the object.
在哪里/如何使用这个默认值而不在 object 中永久更改它。 What I did is the following but there must be a simpler way.
我所做的是以下,但必须有一个更简单的方法。
.
.
.
private int b = 100;
private readonly int defualt_b = 100;
public void Press(int a)
{
...do something...
Send(a, b);
}
public void Press(int a int new_b)
{
...do something...
b = new_b; //set b to be used
Press(a);
b = default_b; //reset back to its default value
}
The context is not completely clear so I am not sure if I understood the problem correctly.上下文并不完全清楚,所以我不确定我是否正确理解了这个问题。 Specifically is the
private int b
used anywhere else and thus needs to be set to some particular value?具体来说,
private int b
是否在其他任何地方使用,因此需要设置为某个特定值? Or is it just a helper field?或者它只是一个辅助字段? If the latter, then just change the dependency between the two overloads:
如果是后者,那么只需更改两个重载之间的依赖关系:
private const int DefualtB = 100;
public void Press(int a)
{
Press(a, DefualtB);
}
public void Press(int a int new_b)
{
...do something...
Send(a, new_b);
}
EDIT: Also this assumes that those "..do something.." blocks in the original code were meant to be the same and done once.编辑:这也假设原始代码中的那些“..do something..”块是相同的并且只完成一次。 If not, then this will be somewhat more complicated.
如果不是,那么这将更加复杂。
Add an optional parameter添加可选参数
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments
public void Press(int a , int new_b = 100)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.