是否可以为C#函数中的参数或可选参数提供默认值? [英] Can I give a default value to parameters or optional parameters in C# functions?

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

问题描述

我可以在C#中提供默认参数吗?

Can I give default parameters in C#?

在C中:

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

我们可以给参数提供默认值吗?在C#中可以吗?如果是这样,我们可以避免函数重载吗?

Can we give parameters a default value? Is it possible in C#? If so, can we avoid overloading functions?

向现有函数添加可选参数始终是一种不好的做法。如果您要处理的项目必须引用具有函数的类,而我们更改了带有可选值的参数,则可能会抛出运行时异常,即找不到该方法。

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

这是因为我们认为如果添加一个额外的可选值,并且该函数在许多地方使用,则无需更改代码。

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 used in many places.

function Add(int a, int b);

这将通过以下方式调用:

This will be called using this way:

Add(10, 10);

但是,如果我们添加这样的可选参数,

But if we add an optional parameter like this,

function Add(int a, int b, int c = 0);

然后编译器期望

Add(10, 10, 0);

实际上,我们这样称呼 Add(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 parameter 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 parameter. Also if you are working with functions having more than one optional parameter, then it's good to pass the value using the name of the parameter.

function Add(int a, int b, int c = 0);

使用以下方式调用此函数总是很好的。

It's always good to call this function using the following way.

Add(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天全站免登陆