C #/NET code streamlining optimization skills (3)

Source: Internet
Author: User
Document directory
  • 1 implicit type
  • 2. LINQ Extension Method
  • 3. Extension Method
  • 4 system. Io. Path
  • 5 generic delegation
  • Summary

The first two articles have introduced 10 tips. This article is the last article in this series and will introduce 5 more tips. These tips are not obvious, and you may know them, but in normal development, they may not be used due to inertia. Therefore, we recommend that you master and use these tips to make our code simpler and easier to maintain.

1 implicit type

First, let's take a look at the concept. The implicit type is not a dynamic type. The implicit type is defined by the keyword var, And the type defined by VAR is still a strong type.

Many people think that using implicit type is a manifestation of laziness. At first I thought so, but think about the development manager that I use the iterative pointer in STL, I understand. See the following code:

for (list<int>::const_iterator it = myList.begin(); it != myList.end(); ++it){    // ...}

In many cases, we will write the following code:

// pretty obviousActiveOrdersDataAccessObject obj = new ActiveOrdersDataAccessObject(); // still obvious but even more typingDictionary<string,List<Product>> productsByCategory =     new Dictionary<string,List<Product>>();

The Type Definition of the code above is obvious. The type is defined by the type. The following attempts to use the VaR keyword to define

// nicer!var obj = new ActiveOrdersDataAccessObject();// Ah, so much nicer!var productsByCategory = new Dictionary<string,List<Product>>();

After the VaR keyword is used, the Code becomes much more concise. the compiler will deduce the type during compilation. The VaR keyword is only equivalent to a placeholder.

Furthermore, using the VaR keyword will provide better readability when we use a generic or LINQ expression. Compare the following two lines of code:

// Implicit var results1 = from P in products where p. value & gt; 100 group P by P. category; // display type ienumerable <igrouping <string, product> results2 = from P in products where p. value & gt; 100 group P by P. category;
2. LINQ Extension Method

In previous coding, we often need to write some own function libraries, such as sorting, grouping, searching, or other algorithms. In addition, it takes us a lot of time to write unit tests for these functions. Some bugs that often plague us are exactly in these methods.

With the introduction of the Extension Method of LINQ, you can use the standard algorithms that are ready-made without having to write them again, which provides great convenience. Orderby () can be used for sorting, where () can be used for query conditions, and select () can be used for selecting attributes of some classes (), you can use groupby () when grouping queries are required. The extension methods in these LINQ have been fully tested, and we do not need to write unit test code for them, there will be no disturbing bugs.

Let's take a look at the example below. assume there is a set list <product>, the set is loaded with the product object, and the product has two attributes: Value and category, now we need to search for data whose value is greater than $100 by category. We may write data as follows:

var results = new Dictionary<string, List<Product>>();foreach (var p in products){    if (p.Value > 100)    {        List<Product> productsByGroup;        if (!results.TryGetValue(p.Category, out productsByGroup))        {            productsByGroup = new List<Product>();            results.Add(p.Category, productsByGroup);        }        productsByGroup.Add(p);    }}

Use the extension method of LINQ

var results = products               .Where(p => p.Value > 100)               .GroupBy(p => p.Category);

You can also write as follows:

var results = from p in products where p.Value > 100 group p by p.Category;
3. Extension Method

The extension method allows us to expand some types of methods, such as some of the extension methods of the above mentioned LINQ. The extension method is a static method and must be in a static class. Take the following example to compile an extension method to convert the object into XML.

public static class ObjectExtensions{    public static string ToXml(this object input, bool shouldPrettyPrint)    {        if (input == null) throw new ArgumentNullException("input");        var xs = new XmlSerializer(input.GetType());        using (var memoryStream = new MemoryStream())        using (var xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding()))        {            xs.Serialize(xmlTextWriter, input);            return Encoding.UTF8.GetString(memoryStream.ToArray());        }    }}

Note that the class containing the extension method must be a static class; the extension method must be a static method; the first parameter of the method must use the this keyword before the type. The following describes how to call the extension method.

// can convert primatives to xmlstring intXml = 5.ToXml();// can convert complex types to xmlstring objXml = employee.ToXml();// can even call as static method if you choose:objXml = ObjectExtensions.ToXml(employee);

In fact, the extension method is just a syntactic sugar, which allows us to add some of our own methods on the type. The proper use of the extension method can bring convenience to our coding, but excessive use will be counterproductive, making the code easier to understand, and our only prompt items will become very large.

4 system. Io. Path

The system. Io. Path Method in. Net has many static methods to process files and paths. Most of the time, we try to manually combine the path with the file name, which makes the generated file path unavailable, because we often ignore that there may be an ending symbol '\' behind the path '\'. Use nowPath. Combine ()This error can be avoided.

string fullPath = Path.Combine(workingDirectory, fileName);

Suppose there is a complete path name with a file name. We need to take the path, file name, or file extension. Many static methods of the path class can meet our needs, as follows:

string fullPath = "c:\\Downloads\\output\\t0.html";// gets "c:\"string pathPart = Path.GetPathRoot(fullPath);// gets "t0.html"string filePart = Path.GetFileName(fullPath);// gets ".html"string extPart = Path.GetExtension(fullPath);// gets "c:\downloads\output"string dirPart = Path.GetDirectoryName(fullPath);

So when we need to perform operations on the file path, we can use the static method of the path class.

5 generic delegation

If you have written or used a class with events or some extension methods of LINQ, many of you may have used delegation directly or indirectly. A delegate can create a type in a powerful way class to describe the signature of a method. Use and call this method at runtime. This is a bit similar to the function pointer in C ++.

The greatest thing about delegation is that it has better reusability than class inheritance. Suppose you want to design a cache class, which has some methods for users to call, however, it depends on whether the cache item expires or is deleted. You provide an abstract method for the user to inherit classes and reload the method, which means a lot of extra work is added.

If a delegate is used, the cache item expiration check can be performed in the specified method, and the delegate method, anonymous delegate, or Lambda expression can be passed or set for calling, in this way, no subclass must be created. We can set the class to be sealed to prevent any unexpected occurrence, so that the class is safer and more reusable.

So what is the relationship between these and generic delegation? Currently, the basic "types" of the three delegates are repeated, and you do not want to write them repeatedly. Generic delegation can improve the readability of our code. Below are the generic delegation types provided by the three net

Action <t>

Predicate <t>

Func <tresult>

For detailed explanations and usage of the above three generic delegation types, click the link to view the msdn

Return to the cache example you just mentioned. You want the cache to accept a cache policy and have a delegate. the return value of the delegate indicates whether the cache has expired. The Code is as follows:

public sealed class CacheItem<T>{    public DateTime Created { get; set; }    public DateTime LastAccess { get; set; }    public T Value { get; set; }}public sealed class Cache<T>{    private ConcurrentDictionary<string, CacheItem<T>> _cache;    private Predicate<CacheItem<T>> _expirationStrategy;    public Cache(Predicate<CacheItem<T>> expirationStrategy)    {        // set the delegate        _expirationStrategy = expirationStrategy;    }    // ...    private void CheckForExpired()    {        foreach (var item in _cache)        {            // call the delegate            if (_expirationStrategy(item.Value))            {                // remove the item...            }        }    }}

 

Now you can create and use cache classes.

var cache = 
new Cache<int>(item => DateTime.Now - item.LastAccess > TimeSpan.FromSeconds(30));

In fact, we can use our imagination to create many expiration policies for cache, but do not use inheritance. Understanding and using generic delegation will increase the reusability of our classes.

Summary

This article is written by referring to the third blog of the foreigners series. It is not a literal translation. For the original article, see the following link. I hope this article will help you.

Link: http://geekswithblogs.net/BlackRabbitCoder/archive/2010/09/09/c.net-five-final-little-wonders-that-make-code-better-3.aspx

 

C #/NET code streamlining optimization skills (1)

C #/NET code streamlining optimization skills (2)

C #/NET code streamlining optimization skills (3)

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.