call C# method from powershell without supplying optional arguments

北慕城南 提交于 2019-11-29 07:32:45

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.

You can simply omit the optional parameters in the call. I modified your example to run it in PS. For example:

$c = @"
    public static class Bar {
        public static void foo(string path, string new_name = null, bool save_now = true)
        {
            System.Console.WriteLine(path);
            System.Console.WriteLine(new_name);
            System.Console.WriteLine(save_now);
        }
    }
"@

add-type -TypeDefinition $c

[Bar]::Foo("test",[System.Management.Automation.Language.NullString]::Value,$false)

This generates the following

test
False

Test was passed explicitly, null is null and had no output, and the save_now evaluated to the default of True.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!