Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

call C# method from powershell without supplying optional arguments

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

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)

but this results in new_name being set as "System.Reflection.Missing" within the function.

Additionally I tried

$obj.foo($path, $null, $false)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...