从PowerShell中调用C#方法不提供可选的参数 [英] call C# method from powershell without supplying optional arguments
问题描述
我有一个C#方法,我从DLL加载带有可选的字符串参数的默认值空
。例如:
I have a c# method I am loading from a dll with optional string arguments that default to null
. For example
public void foo(string path, string new_name = null, bool save_now = true)
{
if(name == null)
new_name = Path.GetFileNameWithoutExtension(path);
...
if(save_now)
Save();
}
我想从一个PowerShell脚本中调用这个,而不是为了提供一个值 NEW_NAME
,但一个 save_now
。按照这个看似非常类似的问题我已经试过
I want to call this from within a powershell script and not supply a value for new_name
but one for save_now
. As per this seemingly very similar question I have tried
$default = [type]::Missing
$obj.foo($path, $default, $false)
但这会导致 NEW_NAME
被设置为System.Reflection.Missing
在函数中。
but this results in new_name
being set as "System.Reflection.Missing"
within the function.
此外我试过
$obj.foo($path, $null, $false)
但这会导致 NEW_NAME
被设置为空字符串,仍然不是空
。我可以设置默认为空字符串,但我想知道是否有真正有使用默认值的好方法。
but this results in new_name
being set to the empty string, still not null
. I could set the default to the empty string, but I was wondering if there was any good way to actually have the default value be used.
推荐答案
没有可以在PowerShell中做。它不支持C#/ VB可选参数。这是在调用方法时程序员不和PowerShell只是没有做到这一点提供的缺省值语言的职责。
No can do in PowerShell. It doesn't support C#/VB optional parameters. It is the duty of the language calling the method to provide the default values when the programmer doesn't and PowerShell just doesn't do that.
这篇关于从PowerShell中调用C#方法不提供可选的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!