首页 / C# / c# – 传递默认参数值(不管它是什么)
c# – 传递默认参数值(不管它是什么)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 传递默认参数值(不管它是什么),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1734字,纯文字阅读大概需要3分钟。
内容图文
![c# – 传递默认参数值(不管它是什么)](/upload/InfoBanner/zyjiaocheng/796/19f47e8b543148d3adf45e8cde90382e.jpg)
//method with an optional parameter
public void DoSomething(int a, int b = 42);
//caller
DoSomething(a, b: default);
这可以用C#完成吗?
您可能会说,“如果您不想设置参数,只需在没有它的情况下调用方法”.但后来我在我的代码中得到了这样丑陋的IF:
//kinda ugly :(
if(parameterIsSet)
DoSomething(a, myValue);
else
DoSomething(a);
当我能做到这一点时:
DoSomething(a, b: parameterIsSet ? myValue : default);
我当然可以这样做:
DoSomething(a, b: parameterIsSet ? myValue : 42);
但我不想在两个地方硬编码“42”
解决方法:
在这种情况下,我通常会在评论中提到使用null.因此代码看起来像这样:
public void DoSomething(int a, int? bOverwrite = null)
{
int b = bOverwrite ?? 42;
// remaining code as before...
}
在这种情况下,您通常会删除parameterIsSet变量并使用null初始化变量并在必要时设置值:
int? myB = null;
if (/* some condition */)
{
myB = 29;
}
DoSomething(a, myB);
如果你还有parameterIsSet,你可以调用这样的函数:
DoSomething(a, parameterIsSet ? b : default(int?));
其他替代品:
如果你有很多这样的参数,为参数创建一个类并在构造函数中设置它的默认值可能更简单:
class DoSomethingParameters
{
public DoSomethingParameters() { A = 12; B = 42; }
public int A { get; set; }
public int B { get; set; }
}
var parameters = new DoSomethingParameters();
parameters.A = /* something */;
if (/* some condition */ {
parameters.B = 29;
}
DoSomething(parameters);
如果有些情况下,丑陋的IF可能是最好的解决方案,你可能会使用相同的条件来初始化b,或者你需要更多的变量来跟踪所有内容,最终的代码甚至可能比丑陋的代码更丑.
if (/* some condition */)
{
int b = some_complet_expression;
DoSomething(a, b);
// Some other stuff here....
}
else
{
DoSomething(a);
// Different stuff here...
}
特别是,如果您在调用后有其他依赖于条件的代码,那么它可能是基本解决方案.每个案例都是具体的.凭借经验,您将学习如何为这种情况编写最佳代码.
内容总结
以上是互联网集市为您收集整理的c# – 传递默认参数值(不管它是什么)全部内容,希望文章能够帮你解决c# – 传递默认参数值(不管它是什么)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。