[More efficient C #] How does a partial class be written?

Source: Internet
Author: User
What is a partial class )?

C. we can use partial classification to distribute a class to multiple class files, so that multiple developers can develop a class library at the same time or expand the class libraries released by other developers. even the code generated by the code generator, such as linq2sql and ADO. to get more efficient development.

Re: The difference between Class and Class file. the class here is what we usually call ordinary class-class, such as abstract class, base class, subclass and so on. class files are the files we usually use when writing classes, such as C. CS, VB. VB.

Although the classification solves the problem that multiple developers develop simultaneously without affecting each other, the constraints are very strict. developers cannot/can hardly communicate with each other, and cannot/can hardly modify the code of the other party. this means that many hooks need to be provided for the other party. these hooks should be implemented in part of the method. developers on the other side can choose to implement or not.

Extend existing classes

The emergence of the Entity Framework greatly reduces our workload, allowing us to focus more on logical implementation and less on data access. for example, we can use linq2sql, which is a lightweight Entity Framework. it generates our access to the data layer. however. sometimes, we need to expand some of our own content, such as methods/attributes. in addition to adding changes directly to the generated class file, we can also use the partial category to expand the functions we need. The former is used every time we follow the new entity. all your extended content will disappear. however, partial classification can still serve you well.

Some methods are provided

Partial methods are the most effective hooks for partial classification. They are similar to method declarations for interfaces.

Keyword: Partial + void + method name + method parameter.

partial void ReportValueChanging(RequestChange args);

Some methods may be part of the class (Implementation) or not part of the class (not implemented), So C # itself imposes some restrictions on some methods.

1. The return type must be void.

2. Some methods cannot be abstract/virtual methods.

3Some methods cannot be used to implement interfaces.

4. The parameter list cannot contain any out parameters because the compiler Cannot initialize these out parameters.

Some methods are used to let users perform things or modify class behaviors: modification methods, event handlers, and constructors.

Modification Method

The modification method refers to the methods for modifying the externally visible states in the class. we can understand it as any state change, because the partial classification implementation of another class file is still part of the class. therefore, we can completely control all internal states of the class.

Generally, the modification method should provide two partial methods for the class. the first one is called before modification to enable the other party (the other developer) to perform legality verification and so on. the second method should be called after the state is modified to allow the other party to change the State accordingly.

public partial class GeneratedStuff    {        private struct ReportChange        {            public readonly int OldValue;            public readonly int NewValue;            public ReportChange(int oldValue, int newValue)            {                this.OldValue = oldValue;                this.NewValue = newValue;            }        }        private class RequestChange        {            public ReportChange Values            {                get;                set;            }            public bool Cancel            {                get;                set;            }        }        partial void ReportValueChanging(RequestChange args);        partial void ReportValueChanged(ReportChange values);        private int storage = 0;        public void UpdateValue(int newValue)        {            RequestChange updateArgs = new RequestChange            {                Values = new ReportChange(storage, newValue)            };            ReportValueChanging(updateArgs);            if (!updateArgs.Cancel)            {                storage = newValue;                ReportValueChanged(new ReportChange(storage, newValue));            }        }    }

If the other class does not provide two methods, the C # compiler will remove this call. The generated method is as follows:

public void UpdateValue(int newValue)        {            RequestChange updateArgs = new RequestChange             {                Values = new ReportChange(this.storage, newValue)            };            if (!updateArgs.Cancel)            {                this.storage = newValue;            }        }

In addition, the two methods are also removed.

We can implement the following hooks:

public partial class GeneratedStuff        {            partial void ReportValueChanging(GeneratedStuff.RequestChange args)            {                if (args.Values.NewValue < 0)                {                    //dosomething...                }                else                {                    //dosomething...                }            }            partial void ReportValueChanged(GeneratedStuff.ReportChange values)            {                //dosomething...            }        }

Here, we use an unmark to allow developers to cancel a modification action. You can also get the same effect by throwing an exception. however. boolean unmark is recommended because it is more lightweight.

Event Handler

In fact, there is no big difference between the event handler and the above method modification. All you need to do is add a delegate event and implement the event mechanism similar to the control.

Constructor Extension

No matter the generated code or the code we write manually, we cannot predict which constructor will be called externally when calling the class. Therefore, we can only do some internal work. For example

public partial class GeneratedStuff        {            partial void Initialize();            public GeneratedStuff()                : this(0)            { }            public GeneratedStuff(int someValue)            {                this.storage = someValue;                Initialize();            }        }

Note! Initialize is called at the end, so that there is an opportunity to check the status of the current object, you can make necessary modifications, or throw an exception when it does not meet the requirements. actually. this type of constructor overload effectively improves the quality of your code (for different constructor, different function blocks are generated in the result Il. this refactoring method actually generates only one function block)

Conclusion

After the above explanation, I believe we have a better understanding of how the classification is made. only by better understanding of the series of "small actions" behind it can we better improve and write more quality code.

From: http://www.dotblogs.com.tw/kongyiyun/archive/2010/10/28/18633.aspx

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.