在函数中只传递我想要的参数

Pass only the arguments I want in a function

假设我有这样一个函数:

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
}

根据我想发送给函数的参数,我只需要做其中的一些事情。其余的应该忽略。

例如:Set(a: 1, c: 'x', f: 1.4f, g: "hello")。只有我发送的参数必须考虑在内,其余的都应该被忽略。我该如何编写这样的函数?


现在我正在将 Dictionary<string, object> 传递给函数并询问“你是否包含此密钥?如果包含,请使用它的值执行某些操作”,但我想知道这是否可能我这样问,因为它看起来更干净。

也许你可以使用 Dictionary<string, dynamic> : 这样你就可以检查键是否有输入的参数。

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

您还可以使用可为空的参数,如果为空则不管理它们:

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
}

我更喜欢最后一个,它更干净、更结实。

带有可选参数:

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