C #7.0 New Feature 2: local method,

Source: Internet
Author: User

C #7.0 New Feature 2: local method,

For details, refer to the Issue: #259.

1.C #7.0 new feature 1: Tuple-based "multiple" Return Value Method

 

In short ,【Local MethodIs to defineMethod.

As a matter of fact, there is nothing new about this new feature, because currently many C # projects can use delegate or delegate-based deformation solutions (lambda, fun <*>, Action, Action <*> ...).

But please think about it carefully. Whether the delegate inside the method body is so perfect ......

 

Current C #

Let's take a look at the practice of setting sub-logical units in a common way.

1 public void Bar () 2 {3 var arr = new int [] {5, 8, 10, 20}; 4 Func <int, string> handler = I =>$ "Current Value: {I }. "; 5 foreach (var I in arr) 6 {7 Console. WriteLine (handler (I); 8} 9}

Does it look like something wrong? Of course, there are many.

1. First, handler cannot perform recursive calls. Check the following code.

1 public int Bar(int n)2 {3     if (n < 0) throw new ArgumentException();4     Func<int, int> handler = n => {5         if (n == 0) return 1;6         return n * handler(n - 1);7     };8     return handler(n);9 }

ThenHandler (n-1)Will report an error (Use of unassigned local variable 'handler'), Because handler has not been assigned a value. Generally, we will try to solve this problem with a very ugly solution:

1 Func<int, int> handler = null;2 handler = n =>{3     if (n == 0) return 1;4     return n * handler(n - 1);5 };

Cough cough, don't say much, the heart of 10 thousand camels rushed over.

2. The use of Lambda expressions is very limited. It does not allow adding behavior modifiers to parameters.Out,Ref,Params, AndOptional Parameter, Cannot appear in the Lambda expression parameter table. You cannot use generic parameters.

3. A delegate object is assigned to point to the function. In order to access the local variable in the Lambda expression, a new object is assigned to it, which indirectly increases the GC pressure.

 

Speaking of this, some children's shoes may naturally come up with a more primitive solution. If a private function is declared externally, there won't be any of the above problems.

1 class Foo 2 {3 public void Bar (int [] arr) 4 {5 foreach (var I in arr) 6 {7 Console. writeLine (Handler (I); 8} 9} 10 11 private string Handler (int I) =>$ "Current Value: {I}"; 12}

This is indeedSimple and crudeBut there are still some small problems.BarThere are referenced methods in the method, and it is not logically necessary to expose themThis. This is actually an unreasonable structure.

 

Local Function)

In C #7.0, code is allowed to declare and call sub-methods directly in a method body (Getter and Setter of methods, constructor, and attribute.

Don't talk nonsense, go to the Code:

1 public void Bar (int [] arr) 2 {3 var length = arr. length; 4 string Length () {5 return $ "length is {length}"; 6} 7 // or: 8 // string Length () >>$ "length is {length}"; 9 Length (); 10}

In the preceding example, Length () is converted to the valuePrivate member Method(IL:This. <Bar> g _ Length (): string ()). However, due to restrictions on the C # language, access is only allowed in the Bar method.

Because this exists in a format similar to the anonymous method, in the current classYou can still define Member methods with the same name and declaration., The local method is executed when it is called from the method body.

Okay.NatureYesMember MethodSo it can avoid the restrictions of [Delegate/Lambda expressions ].Asynchronous, AvailableGeneric, AvailableOut,Ref,Param, YesYield,Feature parametersAnd so on ..

Here is an example:

1 class Foo 2 {3 public IEnumerable <T> Bar <T> (params T [] items) 4 {5 if (items = null) throw new ArgumentException (nameof (items); 6 7 IEnumerable <T2> Enumerate <T2> ([CallerMemberName] T2 [] array) // use the generic and feature parameters 8 {9 // The local method logic 10 foreach (var item in array) 11 {12 yield return item; // use iterator 13} 14} 15 16 return Enumerate <T> (items); // call the local method 17 // return this. enumerate <T> (items); // call the member Method 18} 19 20 IEnumerable <T2> Enumerate <T2> ([CallerMemberName] T2 [] array) 21 {22 // member method logic 23} 24}

 

Summary

This feature shows that C # Is making careful adjustments to functional languages. Recall that many people often make a relatively low-level error in their first ignorance of the code and try to write the function declaration in the Main method. Now it seems that it isPersonThe most direct thinking logic.

 

C #7.0 has not yet been officially released. If you want to experience some features, you can download the VS15 preview version. The syntax for the final release may be different from the one mentioned in this article, please pay attention to the Roslyn project for the latest developments.

Related Article

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.