用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c#代码库

动态生成类

2017-04-01 作者:莫名其妙举报

[c#]代码库

using Microsoft.CSharp;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace 测试程序.帮助
{
    public class CreateNameSpace
    {
        public void mia ( )
        {
            CreateNameSpace CNS = new CreateNameSpace();

            CodeNamespace nspace = CNS.CreateCodeDomHelloDemo();
            Console.WriteLine(CNS.GengerCode(nspace));

            string filename = "HelloWorld.exe";
            CompilerResults result = CNS.Execute(nspace, filename);
            if (result.Errors.HasErrors)//是否存在错误;
            {
                for (int i = 0; i < result.Output.Count; i++)

                    Console.WriteLine(result.Output[i]);

                for (int i = 0; i < result.Errors.Count; i++)

                    Console.WriteLine(i.ToString() + ": " + result.Errors[i].ToString());
            }
            else
            {
                result.GetType();
                System.Diagnostics.Process.Start(filename);//这里比较懒,不想动手去自己打开,呵呵;
            }
            Console.Read();
        }



        /// <summary>
        /// 生成namspace并加入方法
        /// </summary>
        /// <returns></returns>
        public CodeNamespace CreateCodeDomHelloDemo ( )
        {
            //CodeMemberMethod method = new CodeMemberMethod();//方法声明; 
            //method.Name = "SayHello";//  方法名
            //method.Attributes = MemberAttributes.Public | MemberAttributes.Final;//属性
            //method.ReturnType = new CodeTypeReference(typeof(string));//返回类型
            //method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Hello  from code!")));//方法体,只有一句返回语句return "Hello  from code!";

            //CodeEntryPointMethod main = new CodeEntryPointMethod();//主方法Main
            //main.Statements.Add(new CodeVariableDeclarationStatement("HelloWord", "hw",
            //    new CodeObjectCreateExpression("HelloWord", new CodeExpression[] { })));//变量声明:HelloWord hw = new HelloWord();

            //CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("hw"), "SayHello", new CodeExpression[] { });
            //main.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", methodinvoke));
            //main.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "Read"));//两个方法调用:System.Console.WriteLine(hw.SayHello());

            CodeTypeDeclaration helloword = new CodeTypeDeclaration("HelloWord");//类型Class声明
            helloword.Attributes = MemberAttributes.Public;
            CodeMemberField F = new CodeMemberField(typeof(String), "name");
            F.Attributes = MemberAttributes.Public;
            helloword.Members.Add(F);
            helloword.BaseTypes.Add("测试程序.MongoDAL.MongoBaseEntity");
            //helloword .BaseTypes.Add()

            //helloword.Members.AddRange(new CodeTypeMember[] { method, main });//添加方法到clss
            CodeNamespace nspace = new CodeNamespace("HelloDemo1");//命名空间声明
            nspace.Imports.Add(new CodeNamespaceImport("System"));//引入程序命名空间:using System;
            nspace.Imports.Add(new CodeNamespaceImport("测试程序.MongoDAL"));//引入程序命名空间:using System;
            nspace.Types.Add(helloword);//
            return nspace;
        }

        /// <summary>
        /// Print 代码
        /// </summary>
        /// <param name="nspace"></param>
        /// <returns></returns>
        public string GengerCode ( CodeNamespace nspace )
        {
            StringBuilder sb = new StringBuilder();
            System.IO.StringWriter sw = new System.IO.StringWriter(sb);
            CodeGeneratorOptions geneOptions = new CodeGeneratorOptions();//代码生成选项

            geneOptions.BlankLinesBetweenMembers = false;

            geneOptions.BracingStyle = "C";

            geneOptions.ElseOnClosing = true;

            geneOptions.IndentString = "    ";
            CodeDomProvider.GetCompilerInfo("c#").CreateProvider().GenerateCodeFromNamespace(nspace, sw, geneOptions);//代码生成
            sw.Close();
            return sb.ToString();

        }


        /// <summary>
        /// 编译并在内存或io中生成文件
        /// </summary>
        /// <param name="nspace"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public CompilerResults Execute ( CodeNamespace nspace, string filename )
        {
            CodeCompileUnit unit = new CodeCompileUnit();//code编译单元
            unit.Namespaces.Add(nspace);
            CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
            CompilerParameters options = new CompilerParameters();//

            options.GenerateInMemory = true;//是否在内存中生成;
            options.IncludeDebugInformation = true;// 包含调试信息;
            options.ReferencedAssemblies.Add("System.dll");
            //options.OutputAssembly = filename;
            //if (System.IO.Path.GetExtension(filename).ToLower() == ".exe")
            //{
            //    options.GenerateExecutable = true;//true为可执行exe,false:dll
            //}
            //else
            //{
            //    options.GenerateExecutable = false;//true为可执行exe,false:dll
            //}
            return provider.CompileAssemblyFromDom(options, unit);//编译程序集
        }

    }


}


分享到:
更多

网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。