C # tips for the functional

Source: Internet
Author: User

Functional/generic refers to the mechanism by which a data type can be dynamically assigned at run time without specifying a specific parameter type at compile time. Believe that many people are not unfamiliar with generics, such as dictionary,list and other structures belong to the generic type. Interestingly, a function can also be generalized.

If we need a function that is responsible for a certain kind of logical operation (such as sorting, summing, counting, etc.) and not about what type of data is being manipulated, then in order for this function to become more generic, it can be written as a functional.

Give me a simple example that I have encountered:

You often write a file in a project, creating a dictionary of Key-value structures. Writing StreamReader and dicitonary sentences every time will make people feel that the yard is really a boring job. Then wrote a generic load Key-value Dictionary of the functional:

   classCommon {Internal StaticDICTIONARY&LT;T1, t2> loaddict<t1, t2> (stringFileCharSepBOOLHasheader =false,intkeyidx=0,intvalueidx=1) {Dictionary&LT;T1, t2> res =NewDICTIONARY&LT;T1, t2>(); using(StreamReader rd =NewStreamReader (file)) {                stringContent =""; if(hasheader) Rd.                ReadLine ();  while(Content = Rd. ReadLine ())! =NULL)                {                    string[] Words =content.                    Split (Sep); T1 Key= (T1) convert.changetype (Words[keyidx],typeof(T1)); T2 value= (T2) convert.changetype (Words[valueidx],typeof(T2)); if(!Res. ContainsKey (key)) Res.                ADD (key, value); }            }            returnRes; }    }

So just call common.loaddict<string,int> (filename, ...). This function is like a template that determines what type of data to use at run time.

typeof (T1));

If the type operation has more detailed requirements, then you can:

if (typeoftypeof(int))    { ... } Else if (typeoftypeof(double)) {...} Else   ...

C # tips for the functional

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.