简体   繁体   中英

How to bypass function parameters in C#?

I am looking for ways to bypass function parameters. Assume i have a function:

void getDataFromDB(int? ID, string name) {....}

I would like to know the ways bypassing ID or name, smt like this:

entity.getDataFromDB(42);

or

entity.getDataFromDB("Customer");

I won't call function like this:

entity.getDataFromDB(null,"Customer");

I know i can use default values also i can use params for the last parameter. Any good ideas?

C# has two ways to reduce function parameters:

default values (works only if no "standard" parameter follows):

void getDataFromDB(int? ID, string name = "Default") {....}

Method overloads:

void getDataFromDB(int? ID, string name) {....} 
void getDataFromDB(string name) => getDataFromDB(null, name); // overload using lambda

combine named and optional might help.

void getDataFromDB(int? ID = null, string name = null) {....}

allows

getDataFromDB(ID:42);
getDataFromDB(name:"eric");

From what it looks like, you are looking to get data either by name or id (and not both). If that is the case, then these are two distinct operations in my mind which can be solved by method overloading like this:

void getDataFromDB(int id) { … }

void getDataFromDB(string name) { … }

If there is common code between the above two methods then you can keep the common code separate and call from each method.

Personally, I would avoid nullable parameters as we then need to put additional null checks in our method. It open doors for potential bugs.

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