本文介绍了用无限参数创建方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在C#中,您可以这样做:

  foo = string.Format({0} {1} {2} {3} ...,aa,bb,cc...); 

此方法 Format()接受无限参数,这是第一个应该如何格式化字符串,其余的值是要放在字符串中。



今天我遇到了一种情况,我必须得到一组字符串并测试它们,然后我想起了这种语言功能,但我没有任何线索。经过一些不成功的网页搜索之后,我意识到获得一个数组会更加谨慎,这并没有让我感到满意。

Q :如何创建一个接受无限参数的函数?我该如何使用它?

解决方案

使用关键字。



下面是一个例子:

  public int SumThemAll(params int [] numbers)
{
return numbers.Sum();

$ b $ public void SumThemAllAndPrintInString(string s,params int [] numbers)
{
Console.WriteLine(string.Format(s,SumThemAll(numbers)) );


public void MyFunction()
{
int result = SumThemAll(2,3,4,42);
SumThemAllAndPrintInString(结果是:{0},1,2,3);
}

该代码显示了各种各样的内容。首先, params 关键字的参数必须总是最后一个(每个函数只能有一个参数)。此外,您可以通过两种方式调用一个带有 params 参数的函数。第一种方法在第一行 MyFunction 中说明,其中每个数字都作为单个参数添加。但是,它也可以用 SumThemAllAndPrintInString 中所示的数组调用,该函数调用 SumThemAll int [] 称为数字


In C# you can do this:

foo = string.Format("{0} {1} {2} {3} ...", "aa", "bb", "cc" ...);

This method Format() accepts infinite parameters, being the first one how the string should be formatted and the rest are values to be put in the string.

Today I've come to a situation where I had to get a set of strings and test them, then I remembered this language functionality, but I had no clue. After a few unsuccessful web searches, I've realised it would be more prudent to just get an array, which didn't make me quite satisfied.

Q: How do I make a function that accepts infinite parameters? And how do I use it ?

解决方案

With the params keyword.

Here is an example:

    public int SumThemAll(params int[] numbers)
    {
        return numbers.Sum();
    }

    public void SumThemAllAndPrintInString(string s, params int[] numbers)
    {
        Console.WriteLine(string.Format(s, SumThemAll(numbers)));
    }

    public void MyFunction()
    {
        int result = SumThemAll(2, 3, 4, 42);
        SumThemAllAndPrintInString("The result is: {0}", 1, 2, 3);
    }

The code shows various things. First of all the argument with the params keyword must always be last (and there can be only one per function). Furthermore, you can call a function that takes a params argument in two ways. The first way is illustrated in the first line of MyFunction where each number is added as a single argument. However, it can also be called with an array as is illustrated in SumThemAllAndPrintInString which calls SumThemAll with the int[] called numbers.

这篇关于用无限参数创建方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:25