Play to dynamic compilation (ii) combat

Source: Internet
Author: User
Tags abstract bool datetime join json reflection tojson tostring

Dynamic compilation in play: First, in the first, we have learned the simplest use of dynamic compilation. Today directly from the actual combat to see what the real situation of dynamic compilation can bring to us.

The example to be demonstrated today is a situation that is often encountered in actual development, with objects turning to JSON.

I'm going to do an instance of a JSON string in 2 different ways, 1: reflection; 2: Dynamic compilation

Analyze problems

Analyzes the mapping of C # objects in JSON. In general, there are only a few scenarios for JSON objects

A key-value pair object that consists of a number of key objects + value objects, the outermost one is a pair of curly braces, and the key value pairs can also be used as "value objects"

An array object consisting of multiple value objects, the outermost of which is a pair of brackets, and an array object can also be used as a value object.

The key object, consisting of a string that acts as a "key" in the composition of the key value pair

A generic value object, consisting of a single value, such as String,int,bool, which acts as "value" in the key value pair or array object

A special value object, a key value pair object or an array object, which itself can also be used as a value object

The objects in these 4 correspond to C # in each of the following:

A key value pair object-> any object that has a public property, or an object that implements a IDictionary, or an object that has both a key and a value enumeration

An Array object-> an object that implements a IEnumerator or IEnumerable interface

Key Object-> String Object

A generic Value object-> a simple value type under the System namespace, including Int,bool,float,datetime, plus a string

Writing base Classes

To meet all types of transformation requirements, first create an abstract base class Jsonconverter

Using System;
Using System.Collections;
    
Using System.Collections.Generic; namespace Blqw {///<summary>///abstract base class for converting C # to a JSON string, the base class provides a basic type of conversion, or you can override///</summary> Publi
    
        C Abstract class Jsonconverter {public abstract string Tojson (object obj);
        Public Const string Flag = "" "; Base type Convert JSON string//bool value to True,false,//numeric type direct output, date type to specified format string, preceded by double quotation mark//String inside () Replace with (), (") Replace ("), plus Double quotation mark//guid to No-string, preceded by double quotes//methods named according to the From + parameter class name, the lookup method is more convenient for a reflection and dynamic compilation of the public virtual string Frombo Olean (Boolean val) {return val? ' True ': ' false '; Public virtual String Frombyte (Byte val) {return val. ToString (); Public virtual String Fromchar (Char val) {return val. ToString (); Public virtual String Fromdatetime (DateTime val) {return Flag + val. ToString ("Yyyy-mm-dd HH:mm:ss") + Flag; Public virtual String Fromdecimal (Decimal val) {return val. ToString ();
      }  Public virtual String fromdouble (Double val) {return val. ToString (); Public virtual String FromInt16 (Int16 val) {return val. ToString (); Public virtual String FromInt32 (Int32 val) {return val. ToString (); Public virtual String FromInt64 (Int64 val) {return val. ToString (); Public virtual String Fromsbyte (SByte val) {return val. ToString (); Public virtual string Fromsingle (Single-Val) {return val. ToString (); Public virtual String fromstring (string val) {return Flag + val. Replace (@ "", @ ""). Replace ("" ", @" "") + Flag; Public virtual String FromUInt16 (UInt16 val) {return val. ToString (); Public virtual String FromUInt32 (UInt32 val) {return val. ToString (); Public virtual String FromUInt64 (UInt64 val) {return val. ToString (); Public virtual String Fromguid (Guid val) {return Flag + val. 

ToString ("N") + Flag; }//Enum public virtual string Fromenum (enum val) {return Flag + val. ToString () + Flag;  //Convert Array object public virtual string FromArray (IEnumerator ee) {list<string> List =
            New List<string> (); while (EE. MoveNext ()) {list. ADD (Tojson (EE).
            Current)); Return "[" + String.
        Join (",", list) + "]";
            //Convert key value pairs object public virtual string fromkeyvalue (IEnumerable keys, IEnumerable values) {
            list<string> list = new list<string> (); var ke = keys.
            GetEnumerator (); var ve = values.
            GetEnumerator ();
            bool A, B; while ((A = Ke. MoveNext ()) & (b = ve. MoveNext ()) {if (KE). Current = = NULL | | (Ke. Current + "").
                Length = = 0) {throw new ArgumentNullException ("JSON key cannot be null or empty"); } list. ADD (Flag + ke). Current + Flag + ":" + Tojson (ve.
            Current)); } if (a!=b) {throw new ArgumentException ("Inconsistent number of keys and values for key-value pairs"); Return "{" + string.
        Join (",", list) + "}"; }
    }
}

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.