我能给的默认值在C#中的函数参数或者可选参数? [英] Can I give default value to parameters or optional parameters in C# functions?

查看:173
本文介绍了我能给的默认值在C#中的函数参数或者可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以给缺省参数C#?

Can I give default parameters for C#?

用C

  void fun(int i=1)
 {
   printf("%d",i);
 }

我们可以给参数的默认值?是否有可能在C#。如果是这样,我们才能避免过载的功能呢?由于提前

We can give parameters default value? Is it possible in C#. If so, can we avoid overloading functions? Thanks in Advance

修改

它总是一个不好的做法,一个可选的参数添加到现有的功能。如果你是其中有指具有如下功能类项目工作,我们改变一个参数一个可选的值,它可能会抛出运行时异常,该方法是找不到的。

Its always a bad practice to add an optional parameter to an existing function. If you are working in a project which is having refer the class having a function and we changed a parameter with an optional value, it may throws run time exception that the method is not found.

这是因为我们会考虑,如果我们添加一个额外的可选值,还有函数是否在很多地方使用,无需code修改。

this is because we will consider that the if we add an extra optional value, there is no code change required if the function is using in many places.

函数Add(INT A,INT B);
使用这种方式称之为意志
添加(10,10);

但如果我们添加一个可选的参数就是这样,
添加功能(INT A,INT B,INT C = 0);
 那么编译器期望
添加(10,10,0);

but if we add an optional param like this, function Add(int a,int b,int c=0); then the compiler expects Add(10,10,0);.

其实我们呼唤这样的添加(10,10)键,这个功能不会在该类可用,导致运行时异常。

Actually we are calling like this Add(10,10) and this function won't be available in that class and causes a run time exception.

发生这种情况的同时增加了新的参数给一个函数它通过了很多地方打了个电话,我不知道会出现这种情况每次。但我建议你重载函数。

This happens for while adding a new param to a function which called by a lot of places and I not sure this will happen every time. But I suggest you to overload the function.

我们总是需要重载它有一个可选的参数的方法。此外,如果你正在与具有一个以上的可选参数的函数的工作,那么它的良好的使用参数的名称传递值

Always we need to overload the method which has an optional param. Also if you are working with functions having more than one optional parameter , then its good to pass the value using the name of the parameter.

添加功能(INT A,INT B,INT C = 0);
它总是好的使用下面的方法来调用这个函数。
添加(10,20,C:30);

推荐答案

这正是你如何在C#中做,但最先添加的功能,在.NET 4.0中

That is exactly how you do it in C#, but the feature was first added in .NET 4.0

这篇关于我能给的默认值在C#中的函数参数或者可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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