c# - "params"和 "array parameter"有什么区别,应该在什么时候使用?

标签 c#

这两种方法的确切区别是什么?什么时候使用“params”,什么时候使用数组参数?将不胜感激。

// passing array to a method
class Program
{
    static void printarray(int[] newarray)
    {
        int i,sum=0;
        Console.Write("\n\nYou entered:\t");
        for (i = 0; i < 4; i++)
        {
            Console.Write("{0}\t", newarray[i]);
            sum = sum + newarray[i];
        }
        Console.Write("\n\nAnd sum of all value is:\t{0}", sum);
        Console.ReadLine();
    }
    static void Main(string[] args)
    {
        int[] arr = new int[4];
        int i;
        for (i = 0; i < 4; i++)
        {
            Console.Write("Enter number:\t");
            arr[i] = Convert.ToInt32(Console.ReadLine());
        }
        // passing array as argument
        Program.printarray(arr);
        }
    }
}
//using parameter arrays
public class MyClass
{
public static void UseParams(params int[] list)
{
    for (int i = 0; i < list.Length; i++)
    {
        Console.Write(list[i] + " ");
    }
    Console.WriteLine();
}
static void Main()
{ 
    UseParams(1, 2, 3, 4);
    int[] myIntArray = { 5, 6, 7, 8, 9 };
    UseParams(myIntArray);      
}
}

最佳答案

使用 params,您可以传递零个 个参数,但是对于数组,如果它不是可选,您必须提供该参数。对于例如,您可以在不传递任何参数的情况下调用此方法,并且 args 将为空:

public void Foo(params int[] args) { }

Foo(); // no compile-time error, args will be empty

但是如果你使用数组:

public void Foo(int[] args) { }

Foo(); // error: No overload for 'Foo' takes 0 arguments

除此之外两者没有太大区别。 params 只是一个语法糖。

关于c# - "params"和 "array parameter"有什么区别,应该在什么时候使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27375707/

相关文章:

c# - 在 C# 中使用来自另一个方法的正则表达式

c# - 更改准备安装对话框的左侧面板图像-Installer Schield

c# - 通用类型转换

c# - 扩展工具包 SplitButton : use ComboBox ItemsSource as DropDownContent

c# - 将字符串格式 "yyyy-MM-ddTHH:mm:ss.fffZ"转换为日期时间

c# - 当我想双击时如何避免单击?

c# - 来自 OnEventActivityAsync 的数据在第一次之后不会更改 ConversationState

c# - 单 View 渲染(错误?)数字,在 IIS 中是可以的

C#、EF 和 LINQ : slow at inserting large (7Mb) records into SQL Server

c# - 在 C# 中获取/设置文件所有者