WinRT 和可选参数问题

WinRT and Optional parameters issue

我最近遇到一个问题,我无法在 WinRT 项目中使用可选参数。

有什么替代方案吗?我什至尝试了 [optional] 关键字。无效。

以下将无法编译:

void PrintStuffOptional(string stuff, [Optional] int num)
{
    Console.WriteLine(stuff + ": " + num.ToString());
}

导致:

The type or namespace name 'Optional' could not be found (are you missing a using directive or an assembly reference?)

and/or:

The type or namespace name 'OptionalAttribute' could not be found (are you missing a using directive or an assembly reference?)

在文件顶部添加 using System.Runtime.InteropServices; 应该可以解决这些问题。但是,从 C# 4.0 开始,您可以像这样声明可选参数:

void PrintStuff(string stuff, int num = 0)
{
    Console.WriteLine(stuff + ": " + num.ToString());
}

如果调用方法没有为num参数提供值,它将使用默认值0。因此,void PrintStuff() 将以两种方式工作:

PrintStuff("a string to print");
PrintStuff("a string to print", 37239);

在 Windows 运行时组件项目中 public 函数不能有可选参数,只有私有函数可以有。

但如果将该项目转换为 class 库,即使对于 public 函数,您也可以有可选参数。

另一种可能的方法:使用覆盖签名。

public void TheFunction (string param1, string param2)
{
  [...] //processing stuff
}

public void TheFunction (string param1)
{
   return TheFunction(param1, String.Empty);
}