如何使用在C#中的可选参数? [英] How can you use optional parameters in C#?

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

问题描述

注意:这个问题被问在这个时候C#还不支持可选参数(即C#4之前)

Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).

我们正在构建的以编程方式从C#类生成一个Web API。这个类有方法 GetFooBar(int类型的,INT B)和API有一个方法 GetFooBar 服用查询参数如&安培; A = foo的和b =栏

We're building a web API that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b) and the API has a method GetFooBar taking query params like &a=foo &b=bar.

的类需要支持可选参数,这是不是在C#支持的语言。什么是最好的方法呢?

The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?

推荐答案

惊讶没有人提到C#4.0是这样工作的可选参数:

Surprised no one mentioned C# 4.0 optional parameters that work like this:

public void SomeMethod(int a, int b = 0)
{
   //some code
}

编辑:我知道,在这个问题被问的时候,C#4.0不存在。但这个问题仍然位居第一的谷歌C#可选参数所以我想 - 这个答案值得在这里。对不起。

I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.

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

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