当前位置: 首页>>代码示例>>C#>>正文


C# CSharp.CSharpCodeProvider类代码示例

本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider的典型用法代码示例。如果您正苦于以下问题:C# Microsoft.CSharp.CSharpCodeProvider类的具体用法?C# Microsoft.CSharp.CSharpCodeProvider怎么用?C# Microsoft.CSharp.CSharpCodeProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Microsoft.CSharp.CSharpCodeProvider类属于命名空间,在下文中一共展示了Microsoft.CSharp.CSharpCodeProvider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GenerateCode

 public void GenerateCode(CodeDomGenerator.Language language)
 {
     switch (language)
     {
         case CodeDomGenerator.Language.CSharp:
             using (Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
             {
                 System.CodeDom.Compiler.CodeGeneratorOptions opts = new System.CodeDom.Compiler.CodeGeneratorOptions();
                 using (System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(new StringWriter(), opts.IndentString))
                 {
                     tw.Write("continue;");
                     Value = tw.InnerWriter.ToString();
                 }
             }
             break;
         case CodeDomGenerator.Language.VB:
             using (Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider())
             {
                 System.CodeDom.Compiler.CodeGeneratorOptions opts = new System.CodeDom.Compiler.CodeGeneratorOptions();
                 using (System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(new StringWriter(), opts.IndentString))
                 {
                     tw.Write("Continue For");
                     Value = tw.InnerWriter.ToString();
                 }
             }
             break;
         default:
             throw new NotImplementedException(language.ToString());
     }
 }
开发者ID:laymain,项目名称:CodeDomUtils,代码行数:30,代码来源:CodeContinueStatement.cs

示例2: Calculate

        /// <summary>
        /// 动态编译
        /// </summary>
        /// <param name="formula">需编译的内容</param>
        /// <param name="returnType">返回类型</param>
        /// <param name="obj">参数</param>
        /// <returns></returns>
        public static object Calculate(string formula, string returnType, object obj)
        {
            try
            {
                string paramExp = obj.GetType().ToString() + " obj";
                object calculated = null;

                Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters parameter = new System.CodeDom.Compiler.CompilerParameters();
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.GenerateExecutable = false; //<--不要生成 EXE 文件
                parameter.GenerateInMemory = true; //在内存中运行
                string codeDom = GenerateCodeBlocks(formula, returnType, paramExp);
                System.CodeDom.Compiler.CompilerResults result = provider.CompileAssemblyFromSource(parameter,codeDom);//动态编译后的结果

                if (result.Errors.Count > 0)
                {
                    return null;
                }
                System.Reflection.MethodInfo newMethod = result.CompiledAssembly.GetType("Maike.Calculation").GetMethod("dowork");
                calculated = result.CompiledAssembly.GetType("Maike.Calculation").GetMethod("dowork").Invoke(null, new object[] { obj });

                return calculated;
            }
            catch
            {
                return null;
            }
        }
开发者ID:weiliji,项目名称:NFMT,代码行数:36,代码来源:Utility.cs

示例3: GenerateCS

        private void GenerateCS()
        {
            using (Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                CodeGeneratorOptions opts = new CodeGeneratorOptions();
                StringWriter sw = new StringWriter();
                provider.GenerateCodeFromMember(_method, sw, opts);
                StringReader sr = new StringReader(sw.GetStringBuilder().ToString());
                string line = sr.ReadLine();
                while (string.IsNullOrEmpty(line))
                    line = sr.ReadLine();
                int idx = line.IndexOf(" " + _method.Name + "(");
                idx = line.LastIndexOf(' ', idx - 1);

                if (_method.Statements.Count > 0)
                {
                    Text = "partial" + line.Remove(0, idx);
                    Text = sw.GetStringBuilder().Replace(line, Text).ToString();
                }
                else
                {
                    line = "partial" + line.Remove(0, idx);
                    idx = line.LastIndexOf(')');
                    Text = line.Remove(idx + 1) + ";" + Environment.NewLine;
                }
            }
        }
开发者ID:laymain,项目名称:CodeDomUtils,代码行数:27,代码来源:CodePartialMethod.cs

示例4: GenerateCode

 public void GenerateCode(CodeDomGenerator.Language language)
 {
     switch (language)
     {
         case CodeDomGenerator.Language.CSharp:
             using (Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
             {
                 System.CodeDom.Compiler.CodeGeneratorOptions opts = new System.CodeDom.Compiler.CodeGeneratorOptions();
                 using (System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(new StringWriter(), opts.IndentString))
                 {
                     tw.Write("var {0} = ", provider.CreateEscapedIdentifier(VariableName));
                     provider.GenerateCodeFromExpression(InitExpression, tw, opts);
                     tw.Write(";");
                     Value = tw.InnerWriter.ToString();
                 }
             }
             break;
         case CodeDomGenerator.Language.VB:
             using (Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider())
             {
                 System.CodeDom.Compiler.CodeGeneratorOptions opts = new System.CodeDom.Compiler.CodeGeneratorOptions();
                 using (System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(new StringWriter(), opts.IndentString))
                 {
                     tw.Write("Dim {0} = ", provider.CreateEscapedIdentifier(VariableName));
                     provider.GenerateCodeFromExpression(InitExpression, tw, opts);
                     Value = tw.InnerWriter.ToString();
                 }
             }
             break;
         default:
             throw new NotImplementedException(language.ToString());
     }
 }
开发者ID:laymain,项目名称:CodeDomUtils,代码行数:33,代码来源:CodeVarStatement.cs

示例5: createAssembly

        public static void createAssembly(string code)
        {
            string[] sources = { code };
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;
            parameters.GenerateExecutable = (bool)launchArguments.flags["createbinary"];
            if ((bool)launchArguments.flags["createbinary"])
                parameters.OutputAssembly = IO.getExePath();

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("System.Drawing.dll");

            using (Microsoft.CSharp.CSharpCodeProvider CodeProv =
            new Microsoft.CSharp.CSharpCodeProvider())
            {
                CompilerResults results = CodeProv.CompileAssemblyFromSource(parameters, sources);

                if (results.Errors.HasErrors)
                    debug.throwException("Compilation error", String.Join(Environment.NewLine, results.Errors.Cast<CompilerError>().Select(n => n.ToString())), debug.importance.Fatal);

                if (!(bool)launchArguments.flags["createbinary"])
                {
                    Console.WriteLine("Initializing ListSharp");

                    var type = results.CompiledAssembly.GetType("MainClass");
                    var obj = Activator.CreateInstance(type);
                    var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
                    Console.WriteLine(output);
                }
            }
        }
开发者ID:timopomer,项目名称:ListSharp,代码行数:33,代码来源:compiler.cs

示例6: Compile

        public static Assembly Compile(string sourcecode, string[] references, CompileLanguage language = CompileLanguage.CSharp)
        {
            CodeDomProvider comp = null;
            switch (language)
            {
                case CompileLanguage.VisualBasic:
                    comp = new Microsoft.VisualBasic.VBCodeProvider();
                    break;
                case CompileLanguage.CSharp:
                default:
                    comp = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
            }
            CompilerParameters cp = new CompilerParameters();
            foreach (string reference in references)
            {
                cp.ReferencedAssemblies.Add(reference);
            }
            cp.GenerateInMemory = true;

            CompilerResults cr = comp.CompileAssemblyFromSource(cp, sourcecode);
            if (cr.Errors.HasErrors)
            {
                string error = string.Empty;
                foreach (CompilerError err in cr.Errors)
                {
                    error += err.ErrorText + System.Environment.NewLine;
                }
                System.Diagnostics.Trace.WriteLine(error);
                return null;
            }

            return cr.CompiledAssembly;
        }
开发者ID:WrongDog,项目名称:Profiler,代码行数:34,代码来源:RefelctionEventHandler.cs

示例7: CompileFile

        // public ���\�b�h
        public void CompileFile(string filePath)
        {
            if(!File.Exists(filePath)){
                throw new Exception("�t�@�C��������܂��� : " + filePath);
            }

            CodeDomProvider myCompiler;
            string ext = Path.GetExtension(filePath).ToLower();
            switch(ext){
            case JsExt:
                myCompiler = new Microsoft.JScript.JScriptCodeProvider();
                break;
            case CsExt:
                myCompiler = new Microsoft.CSharp.CSharpCodeProvider();
                break;
            case VbExt:
                myCompiler = new Microsoft.VisualBasic.VBCodeProvider();
                break;
            default:
                throw new Exception("���Ή��̃t�@�C���g���q�ł�: " + filePath);
            }

            myPluginDllPath = mySetting.TemplateDir + Path.GetFileNameWithoutExtension(filePath) + ".dll";
            string code = Util.LoadFile(filePath);

            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = true;
            cp.OutputAssembly = myPluginDllPath;
            CompilerResults cr = myCompiler.CompileAssemblyFromSource(cp, code);
            foreach(string s in cr.Output){
                Console.WriteLine(s);
            }

            myCompiler.Dispose();
        }
开发者ID:bakera,项目名称:ECCM,代码行数:36,代码来源:plugincompiler.cs

示例8: execScript

		public bool execScript(string dirPath)
		{
			Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
			// Setup default params for compiler
			CompilerParameters compilerParams = new CompilerParameters();
			compilerParams.GenerateExecutable = false;
			compilerParams.GenerateInMemory = true;
			compilerParams.IncludeDebugInformation = false;
			compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
			compilerParams.ReferencedAssemblies.Add("System.dll");
			compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
			compilerParams.ReferencedAssemblies.Add("NoxShared.dll");
			
			// Compile C# script
			CompilerResults results = csharp.CompileAssemblyFromFile(compilerParams, Directory.GetFiles(dirPath, "*.cs"));

			// Error handling
			if (results.Errors.Count > 0)
			{
				foreach (CompilerError e in results.Errors)
					System.Diagnostics.Debug.WriteLine(String.Format("{0} {1}: {2}", e.FileName, e.Line, e.ErrorText));
				return false;
			}

			// Save assembly in class variable
			scriptAssembly = results.CompiledAssembly;

			// Create Script Instance
			if (initScript())
			{
				// Run Script
				return runScript();
			}
			return false;
		}
开发者ID:2asoft,项目名称:NoxMapEditor,代码行数:35,代码来源:Template.cs

示例9: Main

        static void Main(params string[] args)
        {
            var path = @"..\..\..\Mubble.Data\Raw\Database.dbml";
            var dataTypeAssemblyPath = @"..\..\..\Mubble.Data\bin\Debug\Mubble.Data.dll";
            var dataTypePath = @"..\..\..\Mubble.Data\Generated\DataTypes.xml";
            var output = @"..\..\..\Mubble.Data\Generated\RecordTypes.cs";
            var dataTypeOutput = @"..\..\..\Mubble.Data\Generated\DataTypes.cs";

            LoadDataTypeAssembly(dataTypeAssemblyPath, dataTypePath);

            var cs = new Microsoft.CSharp.CSharpCodeProvider();

            var types = DataObjectHelper.Convert(dataTypePath);

            var c = Generate(types.ToCompileUnit(), cs);

            File.WriteAllText(dataTypeOutput, c);

            var database = DbmlHelper.Convert(path);

            var code = Generate(database.ToCompileUnit(), cs);

            File.WriteAllText(output, code);

            //Console.ReadLine();
        }
开发者ID:mrkurt,项目名称:mubble-old,代码行数:26,代码来源:Program.cs

示例10: Create

        /// <summary>
        /// Writes the code to string in the specific language
        /// and returns the string
        /// </summary>
        public static string Create(Language language, string expression, RegexOptions options)
        {
            CodeCompileUnit unit = Create(expression, options);

            System.Text.StringBuilder builder = new System.Text.StringBuilder();

            using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(builder))
            {
                System.CodeDom.Compiler.ICodeGenerator generator;

                switch (language)
                {
                    case Language.CSharp:
                        System.CodeDom.Compiler.CodeGeneratorOptions genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions();
                        genOptions.BracingStyle = "C";
                        generator = new Microsoft.CSharp.CSharpCodeProvider().CreateGenerator();
                        generator.GenerateCodeFromCompileUnit(unit, stringWriter, genOptions);
                        break;
                    case Language.VisualBasic:
                        generator = new Microsoft.VisualBasic.VBCodeProvider().CreateGenerator();
                        generator.GenerateCodeFromCompileUnit(unit, stringWriter, null);
                        break;
                }

                return builder.ToString();
            }
        }
开发者ID:78655931,项目名称:The-Regulator,代码行数:31,代码来源:CodeGenerator.cs

示例11: Execute

        public override object Execute(string code)
        {
            ICodeCompiler compiler = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();
            CompilerParameters cmpParams = new System.CodeDom.Compiler.CompilerParameters();
            cmpParams.GenerateInMemory = true;
            cmpParams.GenerateExecutable = true;
            //cmpParams.CompilerOptions = "/t:exe";

            foreach (string ass in this._referencedAssemblies)
                cmpParams.ReferencedAssemblies.Add(ass+".dll");

            string codeString = this.GenerateReferenceString();
            codeString = this.InsertCode(code);

            CompilerResults results = compiler.CompileAssemblyFromSource(cmpParams, codeString);

            //			foreach (System.CodeDom.Compiler.CompilerError ce in results.Errors)
            //				this.Put(ce.ErrorText);

            if (results.Errors.Count == 0 && results.CompiledAssembly!=null)
            {
                System.Reflection.MethodInfo methodInfo = results.CompiledAssembly.EntryPoint;
                return methodInfo.Invoke(null, null);
            }
            return null;
        }
开发者ID:timdetering,项目名称:Endogine,代码行数:26,代码来源:ScripterCSharp.cs

示例12: Compile

        public static Assembly Compile(string sSource, string[] referencedAssemblies)
        {
            Microsoft.CSharp.CSharpCodeProvider comp = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            if (!PlatformDetector.IsUnix)
            {
                cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", ""));
            }
            else
            {
                cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file://", ""));
            }
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            foreach (var assembly in referencedAssemblies)
            {

                cp.ReferencedAssemblies.Add(Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory
                    , assembly + ".dll"));
            }
            CompilerResults cr = comp.CompileAssemblyFromSource(cp, sSource);
            if (cr.Errors.HasErrors)
            {
                StringBuilder sError = new StringBuilder();
                sError.Append("Error Compiling Expression: ");
                foreach (CompilerError err in cr.Errors)
                    sError.AppendFormat("{0}\n", err.ErrorText);
                throw new ApplicationException("Ошибка компиляции выражения: " + sError.ToString() + "\n" + sSource);
            }
            return cr.CompiledAssembly;
        }
开发者ID:nico-izo,项目名称:KOIB,代码行数:32,代码来源:DynamicAssemblyHelper.cs

示例13: GenerateCode

 public void GenerateCode(CodeDomGenerator.Language language)
 {
     switch (language)
     {
         case CodeDomGenerator.Language.CSharp:
             if (_csStatement != null)
                 using (Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
                 {
                     System.CodeDom.Compiler.CodeGeneratorOptions opts = new System.CodeDom.Compiler.CodeGeneratorOptions();
                     using (System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(new StringWriter(), opts.IndentString))
                     {
                         provider.GenerateCodeFromStatement(_csStatement, tw, opts);
                         Value = tw.InnerWriter.ToString();
                     }
                 }
             break;
         case CodeDomGenerator.Language.VB:
             if (_vbStatement != null)
                 using (Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider())
                 {
                     System.CodeDom.Compiler.CodeGeneratorOptions opts = new System.CodeDom.Compiler.CodeGeneratorOptions();
                     using (System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(new StringWriter(), opts.IndentString))
                     {
                         provider.GenerateCodeFromStatement(_vbStatement, tw, opts);
                         Value = tw.InnerWriter.ToString();
                     }
                 }
             break;
         default:
             throw new NotImplementedException(language.ToString());
     }
 }
开发者ID:laymain,项目名称:CodeDomUtils,代码行数:32,代码来源:CodeSnippetStatement.cs

示例14: GetCodeDomProvider

 private static CodeDomProvider GetCodeDomProvider(string fileExtension)
 {
     CodeDomProvider cdp;
     switch (fileExtension)
     {
         case ".fsx":
             cdp = CodeDomProvider.CreateProvider("f#");
             break;
         case ".csx":
             cdp = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v3.5" } });
             break;
         case ".vbx":
             cdp = new Microsoft.VisualBasic.VBCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v3.5" } });
             break;
         case ".jsx":
             // Have to figure out better JS support
             cdp = CodeDomProvider.CreateProvider("js");
             break;
         default:
             if (CodeDomProvider.IsDefinedExtension(fileExtension))
             {
                 cdp = CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(fileExtension));
             }
             else
             {
                 throw new ScriptDoesNotCompileException("Unknown extension.");
             }
             break;
     }
     return cdp;
 }
开发者ID:joshrivers,项目名称:FreeSWITCH.Managed,代码行数:31,代码来源:AssemblyCompiler.cs

示例15: ParseString

        public static string ParseString(string input)
        {
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
            };

            var code = @"
            namespace Tmp
            {
                public class TmpClass
                {
                    public static string GetValue()
                    {
                        return """ + input + @""";
                    }
                }
            }";

            var compileResult = provider.CompileAssemblyFromSource(parameters, code);

            if (compileResult.Errors.HasErrors)
            {
                return input;
                //throw new ArgumentException(compileResult.Errors.Cast<System.CodeDom.Compiler.CompilerError>().First(e => !e.IsWarning).ErrorText);
            }

            var asmb = compileResult.CompiledAssembly;
            var method = asmb.GetType("Tmp.TmpClass").GetMethod("GetValue");

            return method.Invoke(null, null) as string;
        }
开发者ID:simul,项目名称:cruise_control,代码行数:34,代码来源:Program.cs


注:本文中的Microsoft.CSharp.CSharpCodeProvider类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。