Rapid Deep cloning using fastreflectionlib

Source: Internet
Author: User
Tags oauth
ArticleDirectory
    • 1. Two simple string extension methods
    • 2. datatable Extension Method

1. Quick assignment of two attributes of the same type of object (fast deep cloning)

Sometimes we construct an instance A and assign a value. Then we create an object B and assign the attribute of object A to object B (the so-called deep clone ). This function is commonly used in development. I remember that I wrote a lot about. Net remoting programming a few years ago.CodeSimilar conversions have been implemented.

The simplest way to achieve this kind of deep cloning is to map attributes one by one and assign values. The advantage of this implementation is that the performance is high (compared with the two methods described below), and the poor is also obvious: if there are many attributes, the amount of code is considerable; if the attributes of a class are added or removed, the code of the assigned value must be changed.

To realize dynamic attribute assignment, the simplest method is reflection (or emit ):

 Reflectclone          /// <Summary>          /// Deep clone          /// </Summary>          /// <Param name = "Source"> original object </param>         /// <Param name = "DEST"> target object </param>          Public   Static   Void Reflectclone ( Object Source, Object DEST) {propertyinfo [] properties = source. GetType (). getproperties (); Foreach (Propertyinfo item In Properties) {propertyinfo property = DeST. GetType (). getproperty (item. Name ); Try {Property. setvalue (DEST, item. getvalue (source,Null ), Null );} Catch {}}}

But as we all know, reflection has certain performance problems, so some cool people have made a fast reflection class library, and the call is also very simple:

 Fastclone          /// <Summary>          /// Deep clone          /// </Summary>          /// <Param name = "Source"> original object </param>          /// <Param name = "DEST"> target object </param>          Public   Static  Void Fastclone ( Object Source, Object DEST) {propertyinfo [] properties = source. GetType (). getproperties (); Foreach (Propertyinfo item In Properties) {propertyinfo property = DeST. GetType (). getproperty (item. Name ); Try {Property. fastsetvalue (DEST, item. fastgetvalue (source ));} Catch {}}}

The call is as follows:

Deepclonetest          Private   Static   Void Test () {person original = New Person {id = 1024, name =" Jeffwong ", Persons = New List <person> { New Person {id = 1023, name =" Jeff ", Persons = New List <person> { New Person {id = 1023, name ="Jeff ",}}}}; Person target = New Person (); // Reflectclone (original, target );              // Console. writeline (target. Persons. Count ); Fastclone (original, target); console. writeline (target. Persons. Count );}

Of course, you can also improve the above two methods to call generic methods. After 10000 tests, the performance improvement is indeed considerable. The application of the quick reflection class library is far more than the implementation of simple and small functions. I have started to use it in a large number in my own DIY Orm, And it is thread safe. The actual usage is very good. Thank you.FastreflectionlibAuthor: Lao Zhao.

By the way, today, coding met the need to implement this function. I asked my colleagues that the methods they provided are similar to the methods mentioned above, so I will make up for it after I come back, I hope it will help you as well.

 

Ii. Extension methods 1. Two simple string extension methods

(1). String inclusion (contains) method extension

First, let's take a look at the simple test results of the native contains method through a piece of code:

 
String STR = "the technical atmosphere of www.cnblogs.com blog Park (cnblogs) is really good! "; String strnull = NULL; string strempty = string. Empty; // console. writeline (Str. Contains (strnull); // throw argumentnullexception if (strempty! = NULL) {console. writeline (Str. contains (strempty); // true} console. writeline (Str. contains (""); // true console. writeline (Str. contains ("cnblogs"); // true

We can see that the contains method of a string is used to return a value indicating whether the specified system. String object exists in this string. If the input parameter value is null, an argumentnullexception exception is thrown. This is inconvenient for our users at ordinary times, because each call to the contains method must undergo non-null judgment and processing. Our general cognition is a real string. If we want to find a null reference string in it (isn't the memory not allocated ?), There is no doubt that it cannot be found. It is only possible to return true directly. At the same time, note that in the returned results, if the value parameter is a null string ("", that is, String. empty), as long as a string is not null, the value is string. in case of empty or "", true is returned when the contains method is called. However, we usually think that if a string (even if the content is a space "") that actually contains content, how can it contain null ("" or string. Empty?

Unless the string itself is empty ("" or string. Empty), contains "" or string. Empty should return true.

Next, we can improve the inclusion relationship according to our own requirements and make the following iscontains extension. In future calls, we can save a lot of judgment and conform to our general Cognition:

StringextensionPublic static class stringextension {public static bool iscontains (this string self, string value) {If (value =Null){ReturnFalse;} If (value. Length = 0)// String. Empty{ReturnSelf. Length = value. length ;}ReturnSelf. Contains (value );}}

The test is as follows:

String STR = "the technical atmosphere of www.cnblogs.com blog Park (cnblogs) is really good! "; String strnull = NULL; string strempty = string. empty; console. writeline (Str. iscontains (strnull); // false console. writeline (Str. iscontains (strempty); // false console. writeline (Str. iscontains (""); // false console. writeline (Str. iscontains ("cnblogs"); // true console. writeline (strempty. iscontains (strempty); // true console. writeline ("". iscontains (strempty); // true console. writeline ("". iscontains (""); // true

(2) isnullorwhitespace Method

In C #4.0, Microsoft has added this static method to the class library (when I tested the effect, I found that the returned results for "" And string. Empty are true ). This method is similar to the isnullorempty method of the string. Now you can see the name at a glance and know what the method is. Before C #4.0, if we judge whether the string is null or a space, we need to write a string help class for processing. Although it is very simple, it is also written as an extension method here:

 
StringextensionPublic Static BoolIsnullorwhitespace (This StringSelf ){If(Self =Null){Return True;}ReturnSelf. Trim (). Length = 0 ;}

The call code is as follows:

 string STR =" blog is very easy to write. If you give me some advice, it's really a lot of color enhancement "; console. writeline (Str. isnullorwhitespace (); // false // console. writeline (string. isnullorwhitespace (STR); // false STR = ""; // console. writeline (string. isnullorwhitespace (STR); // true console. writeline (Str. isnullorwhitespace (); // true STR = NULL; console. writeline (Str. isnullorwhitespace (); // true STR = ""; console. writeline (Str. isnullorwhitespace (); // true // console. writeline (string. isnullorwhitespace (STR); // true STR = string. empty; console. writeline (Str. isnullorwhitespace (); // true // console. writeline (string. isnullorwhitespace (STR); // true 
2. datatable Extension Method

The datatable merging method saw this blog from the garden and suddenly realized that the merge method of the datatable had something in it. According to my practice, the performance is indeed a little unexpected as described in the original article, and then it took several minutes to write it as an extension method:

Datatable Extension   Public   Enum Mergetype {default = 1, importrow = 2 ,} /// <Summary>      /// Datatable merge method extension      /// </Summary>      Public   Static   Class Datatableextention { Public  Static   Void Merge ( This Datatable DT, datatable table, mergetype ){ Switch (Mergetype ){ Default : Case Mergetype. Default: DT. Merge (table ); Break ; Case Mergetype. importrow: Foreach (Datarow item In Table. Rows) {DT. importrow (item );} Break ;}} Public   Static   Void Merge ( This Datatable DT, datarowcollection DRC ){ Foreach (Datarow item In DRC) {DT. importrow (item );}} Public   Static   Void Merge (This Datatable DT, datarow [] rows ){ Foreach (Datarow item In Rows) {DT. importrow (item );}}}

In the garden, he chongtian studied the expansion method with great care and depth, and many implementations were clever and practical. You may wish to refer to it.

 

Iii. Sina Weibo user creation time JSON string converted to datetime

I recently conducted some simple Development Research on oauth and found that the information on various open platforms is uneven, especially. net support is really unfriendly. It takes a lot of time and effort to call a simple small function. Sina is doing a little better, and you can refer to the most development-related materials. However, during development and debugging, it is found that when you log on to Sina Weibo oauth and obtain user information, the object is converted based on the returned JSON string. The creation time (created_at) cannot be converted to the datetime type correctly. For example, after a user authorizes the user to log on to the test website, the website background can obtain personal registration and weibo account information. The JSON format string returned by the Sina Weibo open platform contains the following creation time string:

 
Created_at: Wed May 05 00:00:00 + 0800 2010

It is spoiled by Microsoft. This time format looks like the time obtained by JavaScript, but the careful comparison is really different from that generated by JavaScript (the date format in JS format is like Thu Aug 25 19:40:25 UTC + 0800 ), it seems that it is not as good as the datetime standard format commonly used in C.

After investigation, this method is the legendary UTC, and later it was converted using some JSON tools and found that JSON. net, jayrock. JSON and simple and direct jsonhelper cannot directly convert the string to the datetime data type of C. After searching on the Internet, you can use datetime. parseexact to convert the time format:

      /// <Summary>          /// Convert to datetime according to the UTC time string format          /// </Summary>          /// <Param name = "strtime"> </param>          /// <Returns> </returns>          Public   Static Datetime? Converttotime ( String Strtime) {datetime? Dt = Null ;Try { // Format: Sun Oct 18 00:00:00 + 0800 2009                  If ( String . Isnullorempty (strtime) = False ) {Dt = datetime. parseexact (strtime, "DDD Mmm D hh: mm: ss zzz yyyy" , Cultureinfo. invariantculture );}} Catch {} Return DT ;}

Through the Function Conversion above, one of my Sina Weibo accounts was created on created_at: 2010-05-05.

Time flies.

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.