Division Method in C #3.0

Source: Internet
Author: User

Origin and order

This past weekend is very meaningful to me. First, I got a copy of "God throw the dice?" on Friday. A popular science book about quantum theory, which has been seen from Friday night, has been touched by the inconvenience of many tables. In short, it turns around on the edge of split. On Sunday, I got up early to meet some of my friends and had a private. NET Technical exchange meeting to exchange some of CodePlex applications, Linq and database technologies.

One of the most exciting ones is that Visual Studio 2008 released Beta2 on Saturday. With the lessons of Vista and VS2005, I vowed not to touch any tools and technologies of Beta2 or earlier versions. But it does not mean that I do not care about these technologies. So after VS2008 Beta2 came out, I immediately went down using QQ's download tool, but I reported an error in the installation file, I had to go to MSDN Subcribtion to use Microsoft's own tool to download it again. It was not until Sunday night that the download was completed and installed.

After the installation is complete, I have no strength to go to bed. It is not until today that I can finally touch it. The first step is to see What's New.

Syntax of the Division Method

When we look at What's New in C #, we suddenly find that there is a "Partial Method Definitions" at the end of the New feature list ", but there is no hyperlink to its description like other new features. I searched online and found very little information about the division type. In particular, only CSDN Zhou Rong 《C #3.5 new features in Visual Studio Orcas Beta 1 (2)This division method is mentioned at the end of the article, but it is not further explained. In the English Technical article, there are two good: http://blogs.msdn.com/wesdyer/archive/2007/05/23/in-case-you-haven-t-heard.aspx and.

I took a closer look at MSDN Library for Visual Studio 2008 Beta 2 and finally learned about the language features. Here I will introduce it and hope it will help you.

The definition of a partial method is similar to that of a partial type. You only need to add the partial keyword before the method definition. However, the division method can only be split into two parts: the Definition Declaration (Definition Declaration) and the Implementation Declaration (Implement Declaration ). The definition declaration looks similar to the abstract method:

Partial class CA
{
//...
Private void partial M (); // definition declaration |

The implementation declaration looks like a common method:

Private void partial M () // implementation Declaration
{
// Method body
}

When calling a partial method, it is the same as calling other methods:

CA a = new CA ();
A. M ();

However, if only the definition declaration is used and the implementation declaration is not written, the compiler will not launch (Emit) the metadata of the method and the statement that calls the method and the IL code. In other words, if the implementation declaration is not compiled, the compiled Assembly does not have the M method in the CA type.

Precautions for using the Division Method

The syntax of the division method is very simple, but there are some things to note.

  • If the Implementation declaration is not written, the method call code is not released and the parameter is not evaluated. Therefore, for the following example:

Class CA
{
Partial void M (int I );

Static void Main ()
{
CA a = new CA ();
Int I = 0;
A. M (I ++ );
}
}

The division method M only defines the Declaration and does not implement the Declaration, so it will not launch the code that calls the method:. M (I ++), So I ++ is not evaluated. Therefore, the final I value is still 0. However, if an implementation declaration is written for M,. the M (I ++) code is compiled into the final assembly, and the parameter is also evaluated. The value of I is changed to 1.

  • The partial method can only appear in the partial class.
  • The partial method must be private and the return value type must be void.
  • The partial method can contain parameters, and its parameters can contain this, params, and ref modifiers, but not out modifiers.
  • The division method cannot be virtual.
  • The division method cannot be external (extern.
  • The division method can be static or unsafe.
  • The partial method can be a generic method. The generic constraint must be placed in the definition Declaration, but it can be repeated in the Declaration. In the definition declaration and implementation declaration, the names of type parameters and type parameters are not necessarily the same.
  • The division method cannot be encapsulated into a delegate.

Application scenarios of the Division Method

The original intention of the division method is similar to that of the division type. On the one hand, different developers can write different parts of a type at the same time, and on the other hand, they can separate automatically generated code and user-written code. Like the division type, the division method will also be merged into a method definition at the beginning of compilation. Speculation: from Microsoft's perspective, the second "original intention" may be the true intention.

As a result, the division method has the following application scenarios: (scenario 1 is from the In Case You Haven't Heard article [partition), and scenario 2 is from Visual Studio 2008's Linq to SQL technology, scenario 3 was invented by Anders Liu.

Scenario 1 lightweight event processing

Sometimes, the automatically generated code requires the event-type language structure to notify users to process some operations, but the Code actually used for writing is in the automatically generated type. In this case, you may need to trigger an event or generate a virtual method for user inheritance. However, whether it is an event or an inheritance task, the overhead is relatively large. Therefore, you can use the division method to implement lightweight processing. The following class: (this example references the aforementioned In Case You Haven't Heard article)

Partial class Customer
{
String name;

Public string Name
{
Get
{
Return name;
}
Set
{
OnBeforeUpdateName ();
OnUpdateName ();
Name = value;
OnAfterUpdateName ();
}
}

Partial void OnBeforeUpdateName ();
Partial void OnAfterUpdateName ();
Partial void OnUpdateName ();
}

Three branch methods are defined here, and their meaning is self-evident. If this is the code automatically generated by the system, we only need to implement these partial methods in the partial class Customer in another source code file.

Scenario 2: Customize the Insert, Update, and Delete methods in DataContext

After you add an object class to a project using Linq to SQL, A XxxDataContext class is created, which inherits from the DataContext class and is partial. This class encapsulates specific database operation functions (the entity class only encapsulates data in the database), such as object insertion, update, and deletion.

Next let's take a look at the automatically generated class definition:

[System. Data. Linq. Mapping. DatabaseAttribute (Name = "AdventureWorks")]
Public partial class AdventureWorksDataContext: System. Data. Linq. DataContext
{

Private static System. Data. Linq. Mapping. MappingSource mappingSource = new AttributeMappingSource ();

# Region Extensibility Method Definitions
Partial void OnCreated ();
Partial void InsertAWBuildVersion (AWBuildVersion instance );
Partial void UpdateAWBuildVersion (AWBuildVersion instance );
Partial void DeleteAWBuildVersion (AWBuildVersion instance );
......

Here we can see a series of partial methods. The first OnCreated is actually a lightweight event described in scenario 1, indicating that the DataContext environment object has been created. Other partial methods are used to customize the DTs operation of DataContext. For each table (entity class), a group of InsertXxx, UpdateXxx, and DeleteXxx methods are displayed. If we want to customize the deletion behavior (for example, if we want to set an IsDelete field to true to indicate that it has been deleted), we can extend this partial class in another file, and provide implementation Declaration for the corresponding Delete method.

Scenario 3 new debugging information output method

This is a hypothetical scenario of Anders Liu. With the help of the division method, we can write such code:

Partial class CA
{
Partial void debuuplint (string msg );
...
Void F ()
{
....
Debuuplint ("aaa ");
}
}

Partial class CA
{
# If DEBUG
Partial void debuuplint (string msg );
{
Debug. WriteLine (msg );
}
# Endif
}

The advantage of doing so is that we can say it in turn. if we do not do this, we must add the # if judgment when calling the debugging code each time. In this way, you can write the debugging code as a method and use # if for judgment at one place.

The disadvantage is that the division method must be private, so you must write a set of debugging code for each class.

Summary 

Well, all in all, Anders Liu is talking about the division method in this article.

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.