C#3.5可选和默认值的参数 [英] C# 3.5 Optional and DefaultValue for parameters

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

问题描述

我使用C#.net 3.5来构建应用程序。我一直与在.NET 4.0中可选参数的属性,没有任何问题。我也注意到,与3.5有选择(解决方法)以下属性添加到您的方法,像这样:

I am using C# .net 3.5 to build an application. I have been working with optional parameter attributes in .net 4.0 with no problems. I did notice that with 3.5 there is the option (workaround) to add the following attributes to your method like so:

    public static void MethodName(string name, [Optional][DefaultValue(null)]string placeHolder)
    {

    }

尽管我已经加入了属性的方法,如果我尝试并调用它像这样:

Even though I have added the attributes to the method, if I try and call it like so:

     MethodName("test");

编译器会抱怨说,它正在寻找两个参数,而不是一个。它实际上是可以使用C#.NET 3.5做到这一点?难道我做错了什么?

The compiler will complain that it is looking for two parameters instead of one. Is it actually possible to do this using C# .net 3.5? Am I doing something wrong?

推荐答案

可选参数是C#4.0的语言功能,因此它并不重要的框架,您的目标,但你必须使用VS 2010或更新的版本来进行编译。

Optional parameters are C# 4.0 language feature so it doesn't matter which framework you are targeting, but you have to compile it using VS 2010 or newer.

使用这种语法在VS 2010或更新:

Use this syntax in VS 2010 or newer:

public static void MethodName(string name, string placeHolder = null)
{
    // body
}

这还是中老年之一:

Or this in older one:

public static void MethodName(string name, string placeHolder)
{
    // body
}

public static void MethodName(string name)
{
    MethodName(name, null);
}

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

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