Summary: CLR via C # (Chapter 8): Others (method transfer, out, ref)

Source: Internet
Author: User

Pass parameters to the method by referencing:

1,OutAndRefDifferences:

If the method parameter is markedOut,Parameter can be not initialized, But the object must be assigned a value before the return;

If the method parameter is markedRef, The parameter must be initialized before the call;

That is, keywords are used for a large number of value types.OutAfter,CodeHigher efficiency;

2,CLRAllow method-basedOutAndRefParameters are used to overload methods, but onlyOutAndRefThe difference method is not allowed;

Static VoidAdd (IntI)

{

}

 

Static VoidAdd (Out IntI)

{

}

If you add the following method, an error occurs.

// Error:"Add"It cannot be defined that there are different overload methods on ref and out.

Static VoidAdd (Ref IntI)

{

}

 

To pass a variable number of parameters to the method:

KeywordsParamsIs the last Parameter Applied to the method signature;

Private Static Int32Add (Params Int32[] Values ){

// Note: It is possible to pass the 'values'

// Array to other methods if you want.

 

Int32Sum = 0;

For(Int32X = 0; x <values. length; X ++)

Sum + = values [x];

ReturnSUM;

}

 

Private Static VoidDisplaytypes (Params Object[] Objects ){

Foreach(ObjectOInObjects)

Console. Writeline (O. GetType ());

}

Note: calls to methods that can accept the number of variable parameters may cause some extra performance loss;

The best method is to overload the method;

 

The parameter type of the declaration method:

Specify the weak type whenever possible when declaring the parameter type of the method;

Specify a strong type as much as possible;

To retain more flexibility, you can specify a weak type for the return type;

 

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.