如何在C#中使用可选参数 [英] how to use optional parameter in C#

查看:165
本文介绍了如何在C#中使用可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getData(字符串connString,字符串ProcName,数据集dsData = null)

//第三个参数是可选的

getData(string connString, string ProcName, DataSet dsData=null)

//third parameter is optional

推荐答案

只需使用参数就好像它存在一样-在您的示例中,该方法可以通过两种方式调用:
Just use the parameter as if it was present - in your example, the method can be called in two ways:
getData("Hello", "There");

在这种情况下,执行该方法时dsData将为null,或者

In which case dsData will be null when the method is executed, or

getData("Hello", "There", myDataSet);

在这种情况下,执行该方法时dsData将包含一个DataSet.

in which case dsData will contain a DataSet when the method is executed.


我建​​议您先看看以下链接,

c-4.0-optional-parameters.aspx [ ^ ]

Eric Lippert 在他的博客中讨论了可选参数.

optional-argument-corner-cases- part-one.aspx [
I would suggest please have a look following links,

c-4.0-optional-parameters.aspx[^]

and Eric Lippert discuss about Optional parameter in his blog.

optional-argument-corner-cases-part-one.aspx[^]

Hope it helps :)


这是否回答了您的不完整问题?

Does this answer your INCOMPLETE question?

string connString = ''whatever'';
string procName = ''IDontKnow'';

getDate(connString, procName);

Dataset dataset = null; 

getDate(connString, procName, dataset);



如果您查看代码,则第一个调用不包含数据集作为参数.但是,当调用该函数时,它被隐式地认为是null(不是因为未传递,而是其默认值已指定为null).

总的来说,这里的两个调用将给您相同的结果.即使看代码也有所不同.



if you look at the code, the first call does not contain dataset as paramter. But when the function is called, it is impliclty considered as null (not because it not passed, but its default value has been specified as null).

Overall, the two calls here will give you same result; even though looking at code it differs.


这篇关于如何在C#中使用可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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