简体   繁体   English

C#3.5参数的Optional和DefaultValue

[英]C# 3.5 Optional and DefaultValue for parameters

I am using C# .net 3.5 to build an application. 我正在使用C#.net 3.5来构建应用程序。 I have been working with optional parameter attributes in .net 4.0 with no problems. 我一直在使用.net 4.0中的可选参数属性,没有任何问题。 I did notice that with 3.5 there is the option (workaround) to add the following attributes to your method like so: 我注意到在3.5中有选项(解决方法)将以下属性添加到您的方法中,如下所示:

    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");

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? 实际上是否可以使用C#.net 3.5执行此操作? Am I doing something wrong? 难道我做错了什么?

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. 可选参数是C#4.0语言功能,因此无论您使用哪个框架都无关紧要,但必须使用VS 2010或更新版本进行编译。

Use this syntax in VS 2010 or newer: 在VS 2010或更高版本中使用此语法:

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);
}

The Optional attribute has been available since C# 1.0, and is used when interoperating with external code, it has no effect on method calls in your own code. 自C#1.0以来, Optional属性已经可用,并且在与外部代码进行互操作时使用,它对您自己的代码中的方法调用没有影响。

As there is no optional parameters in C# 3, you can use overloading instead: 由于C#3中没有可选参数,您可以使用重载:

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

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

(Side note: There is no C# version 3.5, that is a framework version.) (旁注:没有C#3.5版,这是一个框架版本。)

Take a look at the following StackOverflow thread: C# Optional Parameters in .net 3.5 看看下面的StackOverflow线程: .net 3.5中的C#可选参数

No use in copy pasting everything which has been said there, as the thread covers pretty much everything. 没有用于复制粘贴已经说过的所有内容,因为该主题几乎涵盖了所有内容。 Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM