Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Code interpreter in C #

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to implement the code interpreter in C#. It is very detailed and has a certain reference value. Friends who are interested must read it!

1. Brief introduction of C # code interpreter

It's a cool feature to be able to execute C # code dynamically. For example, we can enter a line of C # code in the console, and then the program automatically compiles and executes this line of code to show us the results. This is almost the simplest C # code interpreter.

Dynamic execution of C# code is also a very useful function, for example, we can write some code in a file and be loaded by the assembly during execution, so that the code can be changed without aborting the program. When the program loads the code again, the new code is automatically executed.

2. Simple C # code interpreter

UsingSystem

UsingSystem.Collections.Generic

UsingSystem.Reflection

UsingSystem.Globalization

UsingMicrosoft.CSharp

UsingSystem.CodeDom

UsingSystem.CodeDom.Compiler

UsingSystem.Text

UsingSystem.IO

UsingSystem.Xml

NamespaceTest

{

ClassProgram

{

StaticvoidMain (string [] args)

{

Console.Write ("> >")

Stringcmd

Contextcxt=newContext ()

While ((cmd=Console.ReadLine (). Trim ())! = "exit")

{

If (! String.IsNullOrEmpty (cmd))

{

Console.WriteLine ()

Cxt.Invoke (cmd)

}

Console.Write ("\ n > >")

}

}

}

PublicclassContext

{

PublicCSharpCodeProviderCodeProvider {get;set;}

PublicIDictionaryAssemblys {get;set;}

PublicContext ()

{

CodeProvider=newCSharpCodeProvider (newDictionary ()

{{"CompilerVersion", "v3.5"}})

Assemblys=newDictionary ()

Assembly [] al=AppDomain.CurrentDomain.GetAssemblies ()

Foreach (Assemblyainal)

{

AddAssembly (a)

}

AppDomain.CurrentDomain.AssemblyLoad+=newAssemblyLoadEventHandler

(CurrentDomain_AssemblyLoad)

}

PrivatevoidAddAssembly (Assemblya)

{

If (axiomatic null)

{

Assemblys.Add (a.FullName, a)

}

}

VoidCurrentDomain_AssemblyLoad (objectsender,AssemblyLoadEventArgsargs)

{

Assemblya=args.LoadedAssembly

If (! Assemblys.ContainsKey (a.FullName))

{

AddAssembly (a)

}

}

PublicCompilerParametersCreateCompilerParameters ()

{

CompilerParameterscp=newCompilerParameters ()

Cp.GenerateExecutable=false

Cp.GenerateInMemory=true

If (Assemblyscrafts null)

{

Foreach (AssemblyainAssemblys.Values)

{

Cp.ReferencedAssemblies.Add (a.Location)

}

}

Returncp

}

PublicvoidInvoke (Stringcmd)

{

StringinputCmdString=cmd.Trim ()

If (String.IsNullOrEmpty (inputCmdString)) return

StringfullCmd=BuildFullCmd (inputCmdString)

CompilerResultscr=CodeProvider.CompileAssemblyFromSource

(CreateCompilerParameters (), fullCmd)

If (cr.Errors.HasErrors)

{

BooleanrecompileSwitch=true

Foreach (CompilerErrorerrincr.Errors)

{

/ / CS0201:Onlyassignment,call,increment,decrement,andnewobjectexpressionscanbe

/ / usedasastatement

If (! err.ErrorNumber.Equals ("CS0201"))

{

RecompileSwitch=false

Break

}

}

/ / recompile

If (recompileSwitch)

{

StringdynaName= "TempArg_Dynamic_" + DateTime.Now.Ticks.ToString ()

InputCmdString=String.Format ("var {0} =", dynaName) + inputCmdString

InputCmdString+= ";\ nSystem.Console.WriteLine (" + dynaName+ ");"

FullCmd=BuildFullCmd (inputCmdString)

Cr=CodeProvider.CompileAssemblyFromSource (CreateCompilerParameters (), fullCmd)

}

If (cr.Errors.HasErrors)

{

Console.WriteLine ("compilation error:")

Foreach (CompilerErrorerrincr.Errors)

{

Console.WriteLine (err.ErrorNumber)

Console.WriteLine (err.ErrorText)

}

Return

}

}

Assemblyassem=cr.CompiledAssembly

ObjectdynamicObject=assem.CreateInstance ("Test.DynamicClass")

Typet=assem.GetType ("Test.DynamicClass")

MethodInfominfo=t.GetMethod ("MethodInstance")

Minfo.Invoke (dynamicObject,null)

}

PrivateStringBuildFullCmd (StringinputCmdString)

{

StringStringfullCmd=String.Empty

FullCmd+=@ "

NamespaceTest

{

PublicclassDynamicClass

{

PublicvoidMethodInstance ()

{

"+ inputCmdString+@"

}

}

} "

ReturnfullCmd

}

}

}

These are all the contents of the article "how to implement the Code interpreter in C#". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report