简体   繁体   中英

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. If I define b it will used and if not the default. Where/How do I use this default without changing it permanently in the 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? 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. If not, then this will be somewhat more complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM