Pass only the arguments I want in a function

☆樱花仙子☆ 提交于 2021-02-10 14:31:52

问题


Suppose I have a function like that:

public void Set(int a, string b, char c, float d, int e, float f, string g){
    //do something with a
    //do something with b
    //...
    //do something with g
}

I need to do only some of these things, based on the arguments I want to send to the function. The rest should be ignored.

For example: Set(a: 1, c: 'x', f: 1.4f, g: "hello"). Only the arguments I sent must be taken in account, the rest should just be ignored. How can I write such function that behaves like this?


Right now I'm passing a Dictionary<string, object> to the function and asking "Do you contain this key? If you do, execute something with its value", but I'd like to know if it's possible this way I'm asking, as it looks cleaner.


回答1:


Perhaps you can use a Dictionary<string, dynamic> : thus you can check the keys to have typed arguments.

public void Set(Dictionary<string, dynamic> data)
{
  if ( data.ContainsKey("a") )
    Console.WriteLine(data["a"]);
}

You can also use nullable parameters and if null you don't manage them:

public void Set(int? a, string b, char? c, float? d, int? e, float? f, string g)
{
  if ( a.HasValue ) Console.WriteLine(a); // also a.Value
}

I prefer this last that is more clean and robust.

With optional parameters:

public void Set(int? a = null, string b = null, char? c = null, float? d = null, int? e = null, float? f = null, string g = null)
{
}

Set(e: 10);


来源:https://stackoverflow.com/questions/65162175/pass-only-the-arguments-i-want-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!