【问题标题】:Endless method arguments of the same type相同类型的无尽方法参数
【发布时间】:2012-02-01 20:08:21
【问题描述】:

我记得我在某处有红色,您可以创建一个可以接受无休止参数的方法。问题是我不记得该怎么做。我记得是这样的:

private void method(int arguments...)
{
//method body
}

我确定有“...”。我记得当你打电话给method 时,你可以这样称呼它: method(3232);method(123,23,12); 如果有人明白我在说什么,请告诉我该怎么做。

【问题讨论】:

    标签: c# methods arguments


    【解决方案1】:

    你的意思是ParamArray ?(用于 vb.net)

    对于 c#,它似乎是 params

    【讨论】:

    • 那是VB;问题标记为 C#。
    • @phoog,注意到并为 c# 添加了
    【解决方案2】:

    您将使用 params 关键字:

    private void method(params int[] arguments) 
    { 
        //method body 
    }
    

    您可以像这样调用您的方法:method(1,2,3,4,5,6,7,8,9); 并且数组将包含这些数字。 params 关键字必须在一个数组上,如果它不是方法中的唯一参数,它必须是最后一个。参数声明只能有一个参数。

    【讨论】:

    • 好的,但为什么我记得使用...?
    • @Bosak:在 Java 中就是这样完成的(尽管 ... 出现在类型名称之后)。
    • 哦,你可能是对的。我不懂 Java,但我曾经看过一个关于 Java 的剪辑,因为它很像 C#,所以我把它弄糊涂了。
    【解决方案3】:

    您正在寻找函数的无限数量参数的 c/c++ 定义。 你可以在这里看到-http://www.cplusplus.com/reference/cstdarg/va_start/

    实现此类功能的简单方法如下:

    1- 例如定义你的函数

    void logging(const char *_string, int numArgs, ...)
    

    第一个参数是你要使用的字符串。

    第二个参数是你想要给出的无限参数的数量。如果您想计算开关中的占位符(例如 printf 中的 %d、%f),则不必使用此参数 - 提示:在循环中获取每个字符并查看它是否是您的占位符-。

    我想先举一个例子,你如何调用这样的函数:

    logging("Hello %0. %1 %2 %3", "world", "nice", "to", "meet you"); // infinite arguments are "world", "nice", ... you can give as much as you want
    

    如您所见,我的占位符是数字。你可以使用任何你想要的东西。

    2- 有宏,它初始化列表变量并获取参数的值:

    va_list arguments; // define the list
    va_start(arguments, numArgs); // initialize it, Note: second argument is the last parameter in function, here numArgs
    
    for (int x = 0; x < numArgs; x++) // in a loop
    { 
          // Note : va_arg(..) gets an element from the stack once, dont call it twice, or else you will get the next argument-value from the stack
          char *msg = va_arg(arguments, char *); // get "infinite argument"-value Note: Second parameter is the type of the "infinite argument".
          ... // Now you can do whatever you want - for example : search "%0" in the string and replace with msg
    }
    va_end ( arguments ); // we must end the listing
    

    如果您将每个占位符替换为无限参数值并打印新字符串,您应该会看到:

    你好,世界。很高兴认识你

    希望对你有帮助……

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2011-10-15
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多