可选参数在c# [英] Optional parameter in c#

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

问题描述

我在以下代码中使用可选参数。但是显示错误默认参数说明符是不允许的任何人帮助我先生。

i am using optional parameter in the following code. but that shows error "default parameter specifiers are not permitted" anybody help me sir.

public void getno(int pvalu, string pname = "")
{

}


推荐答案

似乎在一些答案中有一些错误信息:

It looks like there's some misinformation in some of the answers:


  • 可选参数引入C#4, 必须使用C#4编译器

  • 可选参数永远在框架,因此您可以定位版本的框架,并仍然使用它们,只要你使用C#4编译器。使用C#4编译器定位.NET 2是完全合理的,然后从VB8引用库的用户仍然可以使用您的可选参数。

  • Optional parameters were introduced into C# 4, so you must use the C# 4 compiler
  • Optional parameters have been in the framework forever, so you can target any version of the framework and still use them, so long as you're using the C# 4 compiler. It's entirely reasonable to target .NET 2 with the C# 4 compiler, and then someone referencing your library from, say, VB8 would still be able to use your optional parameters.

正如别人所说,如果你不使用C#4,或者你希望你的代码被早期的C#代码消耗,重载是使用可选参数的替代方法。 (如果你使用C#4构建一个库,但是一些C#3代码需要调用它,那么这些可选参数在该代码有效地被要求。)

As others have stated, overloads are an alternative to using optional parameters if you're not using C# 4 or if you want your code to be consumed by earlier C# code. (If you build a library using C# 4 but then some C# 3 code needs to call into it, those optional parameters are effectively going to be required as far as that code is concerned.)

(另外,我会认真地重新考虑你的名字...我知道这只是示例代码,但是一般来说,像参数的p的前缀不鼓励作为惯例,类似的方法一般是Pascal -cased。)

(As an aside, I would seriously reconsider your names... I know this is only sample code, but generally speaking prefixes like "p" for parameters are discouraged as a matter of convention, and likewise methods are generally Pascal-cased.)

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

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