仅在函数中传递我想要的参数 [英] Pass only the arguments I want in a function

查看:78
本文介绍了仅在函数中传递我想要的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的函数:

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.

例如: Set(a:1,c:'x',f:1.4f,g:"hello").仅考虑我发送的参数,其余参数应忽略不计.我该如何编写这样的函数?

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?

现在,我要向函数传递 Dictionary< string,object> 并询问您是否包含此键?如果您愿意,请执行具有其价值的东西,但我想知道这种方式是否可行,因为它看起来更干净.

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.

推荐答案

也许您可以使用 Dictionary< string,dynamic> :这样,您可以检查键是否带有类型化的参数.

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"]);
}

您还可以使用可为空的参数,如果为null,则不对其进行管理:

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.

带有可选参数:

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

这篇关于仅在函数中传递我想要的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆