C # Use of Variable Function Parameters

Source: Internet
Author: User

In general, the parameters in the function are determined. However, in some cases, the number of parameters of a function can be changed as needed. To use a Variable Parameter Function, add Params before the parameter.

Here is a demo of mine:

View code

 1   Using System;
2 Using System. Collections. Generic;
3 Using System. LINQ;
4 Using System. text;
5
6 Namespace Demo
7 {
8 Class Program
9 {
10 Static Void Vfunc ( Params String [] Values)
11 {
12 Foreach (String S In Values)
13 {
14 Console. writeline (s );
15 }
16 }
17
18 Static Void Main ( String [] ARGs)
19 {
20 String [] Names = { " Zhm " };
21 String [] Sexs = { " Male " , " Female " };
22 Vfunc (names );
23 Vfunc (sexs );
24 Console. readkey ();
25 }
26 }
27 }

// Output zhm

Male

Female

Of course, a function can also contain variable parameters and constant parameters. Both can be used at the same time.

View code

 1   Using System;
2 Using System. Collections. Generic;
3 Using System. LINQ;
4 Using System. text;
5
6 Namespace Demo
7 {
8 Class Program
9 {
10
11 Static Void Sayhello ( String Name, Params String [] Nichens)
12 {
13 Console. writeline ( " My name {0} " , Name );
14 Foreach ( String Nicloud In Nichens)
15 {
16 Console. writeline ( " My nickname {0} " , Nicloud );
17 }
18 }
19 Static Void Main ( String [] ARGs)
20 {
21 String [] Names = { " Zhm " , " Dd " , " YY " , " II " , " UU " };
22 Sayhello ( " Zhm " , Names );
23
24 Console. readkey ();
25 }
26 }
27 }

However, it is worth noting that variable parameters must be placed at the end of the parameter position in the function. If the above function is written as static void sayhello (Params string [] nichens, string name)

An error is displayed.: "The Params parameter must be the last in the image parameter table ".

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.