. NET Basic Literacy-params

Source: Internet
Author: User

Let's look at one such method

        Public Voidprinttest (string word)        {            Console.WriteLine ("{0}", word);            Console.readkey ();        }

This method can only print out word included characters If you want to print out the word contains the characters out of the adjustment, Then modify the word variable. What's the best way for us to control the number of parameters at random when invoking a method? See params

Look at the optimized Printtest method:

        public void Printtest (params string[]words)        {            string word= "start" +strpersonal;            if (words! = null)            {for                (int i = 0; I <words. Count (); i++)                {                    Word = Word + "," + words[i];                }            }            Console.WriteLine ("{0}", word);            Console.readkey ();        }

When invoking a method, write as:

Mytest.printtest ("Hum"); --Output: Hum mytest.printtest ("Hum", "ha");--Output: Hum, ha mytest.printtest ("Hum", "ha", "Hum Ha");--Output: Hum, ha, hum.

You can also write this:

String[]words = new string[] {"Hum", "ha", "Hum"}; Mytest.printtest (words); --Output: Hum, ha, hum

in General, the number of parameters is fixed. NET provides a more flexible mechanism for implementing variable number parameters, which is to use the params modifier. The advantage of a variable number parameter is that in some cases it is easy to implement an indeterminate number of parameters, such as calculating the weighted sum of arbitrary numbers, linking arbitrary strings to a string, and so on.

when using params , you should also pay attention to some places,

1. The params modified parameter must be a one-dimensional array.

2, params modified parameter array, can be any type, as long as the array type is set to object.

3. The params must be the last one in the parameter list and can only be used once.

. NET Basic Literacy-params

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.