开发者

DefaultParameterValue in C#

开发者 https://www.devze.com 2022-12-08 03:23 出处:网络
I would like to pass in a DateTime as a DefaultParameterValue to my method using DefaultParameterValueAttribute class in the .net framework. Is there a way to do that ?

I would like to pass in a DateTime as a DefaultParameterValue to my method using DefaultParameterValueAttribute class in the .net framework. Is there a way to do that ?

I can pass in a string, boolean and other types liek the code below. I tried passing in Nullable DateTime but did not work.

 object SomeMethod([Optional, DefaultParameterValue("")]string param1,
                  [Optional, DefaultParameterValuefalse)] bool isValid,
                  [Optional, DefaultParameterValue(null开发者_如何学JAVA)] Nullable<DateTime> valuationDate
      );


Until C# 4.0, you best bet is overloads that call into the "real" version:

public void Foo() { Foo(123,"abc");}
public void Foo(int a) { Foo(a, "abc");}
public void Foo(string b) {Foo(123, b);}
public void Foo(int a, string b) { ... your code ... }

In C# 4.0, this will be just:

public void Foo(int a = 123, string b = "abc") { ... }

Called, for example:

Foo();
Foo(456);
Foo(b: "def");


VB.NET will understand this and observe your default, but C# will not.

This is explained by the documentation that describes how this is dependent on the language used to compile to code that calls the decorated method. (http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.defaultparametervalueattribute.aspx)

This will be addressed in the upcoming .NET 4.0 version of C#.

0

精彩评论

暂无评论...
验证码 换一张
取 消