如何在C#中将可选参数的OptionalAttribute设置为当前目录?

Shi*_*iva 1 c# optional-parameters .net-4.5

我正在使用新.Net 4.5功能来像这样在方法签名中将Optional参数指定为OptionalAttribute(请参见MSDN)。

public void GenerateReport(int ReportId, [Optional] string saveToFolderPath)
Run Code Online (Sandbox Code Playgroud)

这很好。

如果saveToFolderPath未传递可选参数,我想saveToFolderPath使用static方法将value设置为当前工作目录Directory.GetCurrentDirectory

当我尝试输入时,出现以下警告/错误。

属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式

如何在C#中设置可选参数的OptionalAttribute

那么,我的选择是否仅限于检查方法内部saveToFolderPath参数(null而不是签名本身)中的参数是否为空?

换句话说,我的问题是,如何将使用OptionalAttribute语法的Optional Parameter的值设置为The Current Directory

Jon*_*eet 5

你不能 可选参数的默认值作为常数存储在IL中。“当前目录” 不是常量,因此不能用作默认值。

最容易想到的是将可选值设置为null,并在这种情况下使用当前目录:

// Use the C# syntax for this, rather than specifying the attribute explicitly
public void GenerateReport(int ReportId, string saveToFolderPath = null)
{
    saveToFolderPath == saveToFolderPath ?? Directory.GetCurrentDirectory();
    ...
}
Run Code Online (Sandbox Code Playgroud)

我不认为您可以使用属性来显式地进行任何操作,而使用C#语法来处理可选参数则无法进行任何操作,因此您可能会习惯于此。

那的确意味着,任何明确通过的人null都会得到相同的行为,但是,这可能不是您想要的。如Servy所示,另一种选择是使用两个重载。


Ser*_*rvy 5

如果您希望选项参数的默认值是非编译时常量,则需要改用方法重载:

public void GenerateReport(int ReportId)
{
    GenerateReport(ReportId, Environment.CurrentDirectory);
}
public void GenerateReport(int ReportId, string saveToFolderPath)
{
}
Run Code Online (Sandbox Code Playgroud)