【问题标题】:c# call a method with paramaters as a string variablec#调用一个方法,参数为字符串变量
【发布时间】:2017-08-24 03:20:18
【问题描述】:

您好,我想调用一个方法:

public string MyMethod($MyVariable)
{
}

其中变量 $MyVariable 包含函数的所有参数,即:

$MyVariable = "argument1,argument2,argumentn"

这可能吗,我需要特殊语法吗?

【问题讨论】:

  • 不...只是将字符串放在 Myvariable 之前...然后丢失 $。
  • public string MyMethod(params string[] parameters)
  • 向我们展示一些可以编译的代码,$ 的东西没有意义。你确定这是 C# 吗?

标签: c# variables methods dynamic call


【解决方案1】:

我不知道你是想传递一个包含所有参数的字符串,还是多个参数。

单参数

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

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

    return "whatever your string was";
}

输出:

参数1,参数2,...

多个参数

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";
}

输出:

参数1
论据2
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2011-09-17
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多