本文介绍了C# 是否支持可变数量的参数,以及如何支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

C# 是否支持可变数量的参数?

Does C# support a variable number of arguments?

如果是,C#如何支持变量数量的参数?

If yes, How does C# support variable no of arguments?

有哪些例子?

可变参数有什么用?

EDIT 1:有哪些限制?

EDIT 2:问题不是关于可选参数而是关于变量参数

EDIT 2: The Question is not about Optional param But Variable Param

推荐答案

是的.经典示例将是 params object[] args:

Yes. The classic example wourld be the params object[] args:

//Allows to pass in any number and types of parameters
public static void Program(params object[] args)

一个典型的用例是将命令行环境中的参数传递给程序,在那里您将它们作为字符串传递.然后程序必须正确地验证和分配它们.

A typical usecase would be passing parameters in a command line environment to a program, where you pass them in as strings. The program has then to validate and assign them correctly.

限制:

  • 每个方法只允许一个 params 关键字
  • 它必须是最后一个参数.

在我阅读您的编辑后,我做了我的.下面的部分还介绍了实现可变数量参数的方法,但我认为您确实在寻找 params 方式.

After I read your edits, I made mine. The part below also covers methods to achieve variable numbers of arguments, but I think you really were looking for the params way.

也是比较经典的方法之一,称为方法重载.您可能已经经常使用它们:

Also one of the more classic ones, is called method overloading. You've probably used them already a lot:

//both methods have the same name and depending on wether you pass in a parameter
//or not, the first or the second is used.
public static void SayHello() {
    Console.WriteLine("Hello");
}
public static void SayHello(string message) {
    Console.WriteLine(message);
}

最后但并非最不重要的一个:可选参数

//this time we specify a default value for the parameter message
//you now can call both, the method with parameter and the method without.
public static void SayHello(string message = "Hello") {
    Console.WriteLine(message);
}

http://msdn.microsoft.com/en-us/library/dd264739.aspx

这篇关于C# 是否支持可变数量的参数,以及如何支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:51