. NET Dynamic scripting language script. NET application example

Source: Internet
Author: User

Continue with the previous two articlesArticleDynamic scripting language topic 《. NET Dynamic scripting language script.. Net Quick Start and 《. NET Dynamic scripting language script. net Development Guide, continue to learn scripts.. net.

Type Definition

Script. NET is not an OOP language, but can be simulated by property bags.

 
Vector = [X-> 4, Y-> 3, length-> function () {math. SQRT (Me. x ^ 2 + me. y ^ 2) ;}]; console. writeline (vector. length ());

This sectionCodeThe output is 5, where the definition of the vector type is simulated and the length of the vector is calculated by defining the function length. Me is similar to this in C.

Let's take a look at the example below, which also simulates the type definition of OOP language.

Stack = [test-> function (){Return 'Hello Test';}];ReturnStack. Test ();

Run this code in script. Ide. The result is the output string Hello test.

In property bags, use-> to point to the defined function name, and compare the function definition defined in script. Net syntax.

 
Function swap (array, a, B) {TMP = array [a]; array [a] = array [B]; array [B] = TMP ;}

You can also define functions in the syntax format similar to JavaScript Functions.

 
Test = function (item) {Y = item ;};
 
 
Function scopes

Let's take a look at an image of scope in the script. Net official document.

ProgramIn the language, scope is used to parse name references. For example, the following code is available in C #:

  class  program { static   void  main ( string  [] ARGs) { int  X = 100; add ();}  static   int  Add () { int  X = 10;  return  X ;}

By running the code, you can know that the value returned by the add method (or function) is 10. C # is a pure OOP language with no global variables. The C language can include global variables, which are much more complicated in terms of parsing NAME references (scope. Sorry, it is quite unfamiliar with the C language and cannot be used as an example.

Let's look at several examples to deepen our understanding of scope.

 
A = 4; B = 2; C = 3; function test1 (a, B) Global (c) {c = a + B; A = 15;} console. writeline (test1 (2, 3 ));
Console. writeline ();
 
Console. writeline (B );
 
Console. writeline (C );

The function definition is slightly changed this time. After the function parameter list, global (c) is added to indicate that its scope is global and global.

Run in script. Net ide. The result is as follows:

15425

If the return statement is not defined for a function, the value of the last expression is the return value of the function. Therefore, test1 (2, 3) returns a = 15, and the result is 15. The scope of A and B is local, and the changes to it in the function will not affect its value (this is the stack definition of C language, call the function, and take a copy of the parameter, and push the parameters to the same stack. If you want to pass in a reference to the parameter variable, instead of a copy, you need to use a pointer ). C. Because it is defined as global, the changes made to test1 will still be retained, so the last row outputs result 5.

If you have not forgotten the contents of the previous contract section, you should be able to understand the following Function Definition Format.

A = 4; B = 2; C = 3; function test1 (a, B) Global (c) [pre (a> 0); Post (); invariant ();] {c = a + B; A = 15 ;}

If global is applied in the function, but its variables are not defined, the following statement will throw the scriptidnotfoundexception exception.

 
Test = function (item) Global (y) {Y = item ;}; test (2 );

In C, you must first define the function and then call the function. Otherwise, the function definition cannot be found. If you want to call the function before defining the function statement, you need to declare it. In Visual C ++, it is also required to declare the types and functions in the. h file, which is implemented in the. cpp file, but not in C.

See the following code.

 
ReturnF (); function f (){Return1 ;}

Before defining the statement code of function f, you can call it without writing any statements, thanks to the development of compilation technology.

 

Operator assigns operators Dispatching

In the program language, if the operator number (+,-% ...) If the types on the left and right sides are different, type conversion will occur. This also involves operator number overloading. For example, the plus sign + can be applied to data operations or string connections. See the following example to understand operator assignment.

Console. writeline (1 + 1 ); // 2 Console. writeline (1.2 + 1 ); // 2.2 Console. writeline ( '1' + 1 ); // 11 Console. writeline ( 'Hello' + 1 + 'Text' ); // Hello 1 Text Console. writeline (10-1 ); // 9 Console. writeline (1.2-1 ); // 1.2-1 = 0.2 Console. writeline (10*12 ); // 10*12 Console. writeline (3.2*3 ); // (Double) 3.2*3 = 9.6 Console. writeline (3.5*21.5 ); // (Double) 3.5*21.5 = 75.25 Console. writeline (6/2 ); // 6/2 = 3 Console. writeline (10/12 ); // 10/12 = 0 Console. writeline (45.43/12.3 ); // (Double) 45.43/12.3 =. 69349593495935 Console. writeline (3.5/21 ); // (Double) 3.5/21 = 0.166666666666667 Console. writeline (3/21. 2 ); // 3/(double) 21.2 = 0 = 0.141509433962264 Console. writeline (6% 2 ); // 6% 2 = 0 Console. writeline (10% 12 ); /// 10% 12 = 10 Console. writeline (45.43% 12.3 ); // (Double) 45.43% 12.3 = 8.53 Console. writeline (6 ^ 2 ); // Math. Pow (6, 2) = 36 

If the operator number does not support the data types on both sides, an exception notsupportedexception is thrown. For example

 
Console. writeline ('1'-1); // notsupportedexception
 
 
Scripting runtime Runtime

The author of script. Net drew a beautiful runtime diagram to explain their role.

 
This figure can explain the following code. Why do you not need to add the definition of the test Type? You can also find the test type.
// Runtimehost. addtype ("testt", typeof (testt ));Test rez = (TEST) script. runcode (@ "A = new test (); A. value = 'test'; A. intval = 20; return ;")

The cause is assemblymanager, which adds the assembly in the current app domain and the type definition to the script runtime.

If you still remember the runtimeconfig. xml file mentioned in the previous article, it loads the required assembly, type ing, and initial code snippet at runtime startup. You can modify the embedded resource file in the scriptdotnet project to achieve the preliminary test.

You can also use the following method to load the custom runtime configuration.

 
Public StaticStream testconfig {get {stream configstream = assembly. getexecutingassembly (). getmanifestresourcestream ("Unittests. testconfig. xml"); Configstream. Seek (0, seekorigin. Begin );ReturnConfigstream ;}} runtimehost. assemblymanager =NewBaseassemblymanager (); runtimehost. initialize (testconfig );

Runtimehost. initialize (); this statement must be called. It can also be used to pass in stream objects.

Runtimehost. initialize (NewFilestream ("Runtimeconfig. xml", Filemode. Open ));

You can block the load assembly as defined in the following code.

Runtimehost. assemblymanager. beforeaddassembly + = (S, e) => {If(E. Assembly. fullname! ="System. Data, version = 2.0.0.0, culture = neutral, publickeytoken = b77a5c561934e089")Throw NewException ();};
 
 
Custom operator custom Operator

Let's take a look at the example of an operator. I want 1234 and $1234 to indicate the number of currencies. $ is not embedded in the system operator. We need to use the following method to add it.

 Private   Class Dollarhandler: ioperatorhandler { Public   Object Process (handleoperatorargs ARGs ){ If (ARGs. Arguments! =Null & Amp; args. Arguments. Length = 1 ){ String   Value = ( String ) Args. Arguments [0]; args. Cancel = True ; Return   Int . Parse ( Value );} Throw   New Notsupportedexception () ;}} runtimehost. initialize (testconfig); runtimehost. registeroperatorhandler ( "$" , New Dollarhandler (); Script script = script. Compile (@ "Return $'000000 ';" ); Object Rez = script. Execute ();

The debug Code shows that the rez value is 1234 and no exception is thrown.

 

Extended Function custom type's Function

In the following example, the built-in types of script. Net do not have the tostring function. I want to extend it and add the tostring function.

Private ClassMybinder: objectbinder {Public Override BoolCanbind (memberinfo member ){If(Member. Name ="Tostring")Return True;Return Base. Canbind (member );}Public ObjectConvertor (Object Value, Type targettype ){Return Value. Tostring ();}}

Let's call the function added above for example.

 runtimehost. binder =  New  mybinder (); runtimehost. initialize (testconfig); Script script = script. compile ( @ "B = 'a'; B. tostring (); money = 100; money. tostring (); ");  Object  OBJ = script. execute (); 

The value of OBJ returned is 100. This reminds me of the C # extension method, as shown below:

  Public   class  decimalhelper { Public   static   string  tostring ( This   decimal  OBJ) { return  obj. tostring () ;}}

The following code can be compiled

 
DecimalMoney = 100;StringHowmuch = money. tostring ();

The two are very similar. The decimal in C # has the object system. decimal to express the same meaning, and script. net does not have the object concept, only the basic data types of double, long, String, bool and array, can also achieve the function of extension.

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.