call C# method from powershell without supplying optional arguments

后端 未结 2 473
余生分开走
余生分开走 2020-12-18 08:13

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         


        
2条回答
  •  天涯浪人
    2020-12-18 08:57

    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.

提交回复
热议问题