简体   繁体   中英

c# call a method with paramaters as a string variable

Hi i want to call a method:

public string MyMethod($MyVariable)
{
}

Where the variable $MyVariable contains all arguments for the function ie:

$MyVariable = "argument1,argument2,argumentn"

Is this possible, do i Need Special Syntax?

I can't tell if you want to pass one string containing all parameters, or multiple parameters.

Single parameter

public void Main()
{
    MyMethod("argument1, argument2, ...");
}

public string MyMethod(string parameters)
{
    Console.Write(parameters);

    return "whatever your string was";
}

Output:

argument1, argument2, ...

Multiple parameters

public void Main()
{
    MyMethod("argument1", "argument2", "...");
}

public string MyMethod(params string[] parameters)
{
    foreach (var parameter in parameters)
    {
        Console.Write(parameter);
    }

    return "whatever your string was";
}

Output:

argument1
argument2
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM