예제 #1
0
    public Type GetType(string code, string typeName = default)
    {
        OopOperator oopOperator = OopOperator.UseCompiler(AssemblyBuilder, OptionAction);
        string      result      = oopOperator
                                  .GetUsingBuilder()
                                  .Append(code).ToString();

        oopOperator.AssemblyBuilder.Add(result, oopOperator.Usings);

        var text = result;

        if (typeName == default)
        {
            typeName = ScriptHelper.GetClassName(text);
            if (typeName == default)
            {
                typeName = ScriptHelper.GetInterfaceName(text);
                if (typeName == default)
                {
                    typeName = ScriptHelper.GetStructName(text);
                    if (typeName == default)
                    {
                        typeName = ScriptHelper.GetEnumName(text);
                    }
                }
            }
        }

        return(oopOperator.AssemblyBuilder.GetTypeFromShortName(typeName));
    }
예제 #2
0
        public void TestBuilder3()
        {
            OopOperator builder = new OopOperator();
            var         script  = builder
                                  .Namespace <string>()
                                  .OopAccess("")
                                  .OopName("TestUt3")
                                  .ChangeToInterface()
                                  .Ctor(item => item
                                        .MemberModifier(Modifiers.Static)
                                        .Param <string>("name")
                                        .Body("this.Name=name;"))
                                  .OopBody(@"public static void Test(){}")
                                  .PublicStaticField <string>("Name")
                                  .PrivateStaticField <int>("_age")
                                  .Script;

            Assert.Equal(@"using System;
namespace System{
interface TestUt3{
public static String Name;
private static Int32 _age;
public static void Test(){}static TestUt3(String name){
this.Name=name;}
}}", script);
        }
예제 #3
0
        public void TestBuilder4()
        {
            OopOperator builder = new OopOperator();
            var         script  = builder
                                  .HiddenNameSpace().ChangeToEnum()
                                  .Public.OopName("EnumUT1")
                                  .EnumField("Apple")
                                  .EnumField("Orange")
                                  .EnumField("Banana")
                                  .Script;

            Assert.Equal($"public enum EnumUT1{{{Environment.NewLine}Apple,{Environment.NewLine}Orange,{Environment.NewLine}Banana{Environment.NewLine}}}", script);
        }
예제 #4
0
파일: OopTest.cs 프로젝트: zgmqdl/Natasha
        public void TestBuilder5()
        {
            OopOperator builder = new OopOperator();
            var         script  = builder
                                  .HiddenNameSpace().ChangeToEnum()
                                  .OopAccess(AccessTypes.Public).OopName("EnumUT1")
                                  .EnumField("Apple", 1)
                                  .EnumField("Orange", 2)
                                  .EnumField("Banana", 4)
                                  .Builder().Script;

            Assert.Equal($"public enum EnumUT1{{{Environment.NewLine}Apple=1,{Environment.NewLine}Orange=2,{Environment.NewLine}Banana=4{Environment.NewLine}}}", script);
        }
예제 #5
0
 public void Builder(string typeName, Action <OopOperator> action)
 {
     if (_typeCache.ContainsKey(typeName))
     {
         OopOperator @operator = new OopOperator();
         @operator.UseType(_typeCache[typeName], typeName);
         action?.Invoke(@operator);
         this[typeName] = @operator.Script;
     }
     else
     {
         throw new Exception($"Can't find type:{typeName}!");
     }
 }
예제 #6
0
        public void TestBuilder1()
        {
            OopOperator builder = new OopOperator();
            var         script  = builder
                                  .Public.Static
                                  .Using <OopBuildTest>()
                                  .Namespace("TestNamespace")
                                  .OopName("TestUt1")
                                  .OopBody("public static void Test(){}")
                                  .PublicStaticField <string>("Name")
                                  .PrivateStaticField <int>("_age")
                                  .Script;

            Assert.Equal($@"using NatashaUT;{Environment.NewLine}using System;{Environment.NewLine}namespace TestNamespace{{{Environment.NewLine}public static class TestUt1{{{Environment.NewLine}public static String Name;{Environment.NewLine}private static Int32 _age;{Environment.NewLine}public static void Test(){{}}{Environment.NewLine}}}}}", script);
        }
예제 #7
0
        public void TestBuilder4()
        {
            OopOperator builder = new OopOperator();
            var         script  = builder
                                  .HiddenNameSpace().ChangeToEnum()
                                  .OopAccess(AccessTypes.Public).OopName("EnumUT1")
                                  .EnumField("Apple")
                                  .EnumField("Orange")
                                  .EnumField("Banana")
                                  .Builder().Script;

            Assert.Equal(@"public enum EnumUT1{
Apple,
Orange,
Banana
}", script);
        }
예제 #8
0
        public void TestBuilder3()
        {
            OopOperator builder = new OopOperator();
            var         script  = builder
                                  .Namespace <string>()
                                  .OopName("TestUt3")
                                  .ChangeToInterface()
                                  .Ctor(item => item
                                        .StaticMember
                                        .Param <string>("name")
                                        .Body("this.Name=name;"))
                                  .OopBody("public static void Test(){}")
                                  .PublicStaticField <string>("Name")
                                  .PrivateStaticField <int>("_age")
                                  .Script;

            Assert.Equal($@"using System;{Environment.NewLine}namespace System{{{Environment.NewLine}interface TestUt3{{{Environment.NewLine}public static String Name;{Environment.NewLine}private static Int32 _age;{Environment.NewLine}public static void Test(){{}}static TestUt3(String name){{{Environment.NewLine}this.Name=name;}}{Environment.NewLine}}}}}", script);
        }
예제 #9
0
        public void TestBuilder1()
        {
            OopOperator builder = new OopOperator();
            var         script  = builder
                                  .Using <OopTest>()
                                  .Namespace("TestNamespace")
                                  .OopAccess(AccessTypes.Public)
                                  .OopModifier(Modifiers.Static)
                                  .OopName("TestUt1")
                                  .OopBody(@"public static void Test(){}")
                                  .PublicStaticField <string>("Name")
                                  .PrivateStaticField <int>("_age")
                                  .Builder()
                                  .Script;

            Assert.Equal(@"using NatashaUT;using System;namespace TestNamespace{public static class TestUt1{public static String Name;private static Int32 _age;public static void Test(){}}}", script);
            Assert.Equal("TestUt1", builder.GetType().Name);
        }
예제 #10
0
        public void Test1()
        {
            OopOperator builder = new OopOperator();

            builder
            .Using <OopTest>()
            .Namespace("TestNamespace")
            .OopAccess(AccessTypes.Public)
            .OopModifier(Modifiers.Static)
            .OopName("TestExceptionUt1")
            .OopBody(@"public static void 1 Test(){}")
            .PublicStaticField <string>("Name")
            .PrivateStaticField <int>("_age")
            .Builder();
            var type = builder.GetType();

            Assert.Null(type);
            Assert.Equal(ComplieError.Syntax, builder.Complier.Exception.ErrorFlag);
        }
예제 #11
0
        public void Test2()
        {
            OopOperator builder = new OopOperator();

            builder.AssemblyBuilder.Syntax.ErrorBehavior = ExceptionBehavior.None;
            builder
            .Public()
            .Static()
            .Using <ClassExceptionTest>()
            .Namespace("TestNamespace")
            .Struct()
            .DefinedName("TestExceptionUt2")
            .Body(@"public static void 1 Test(){}")
            .PublicStaticField <string>("Name")
            .PrivateStaticField <int>("_age")
            .BuilderScript();
            var type = builder.GetType();

            Assert.Null(type);
            Assert.Equal(ExceptionKind.Syntax, builder.Exception.ErrorFlag);
        }
예제 #12
0
        public void InterfaceSet()
        {
            OopOperator <ITest> interfaceBuilder = new OopOperator <ITest>();

            interfaceBuilder.ClassName("UTestClass");
            interfaceBuilder["MethodWidthReturnInt"]    = "return 123456;";
            interfaceBuilder["MethodWidthReturnString"] = "return \"test\";";
            interfaceBuilder["MethodWidthParamsRefInt"] = "i+=10;";
            interfaceBuilder["MethodWidthParamsString"] = "return str+\"1\";";
            interfaceBuilder["MethodWidthParams"]       = "return a.ToString()+str+b.ToString();";
            interfaceBuilder.Compile();
            var test  = interfaceBuilder.Create("UTestClass");
            int testi = 1;

            test.MethodWidthParamsRefInt(ref testi);
            Assert.Equal(123456, test.MethodWidthReturnInt());
            Assert.Equal("test", test.MethodWidthReturnString());
            Assert.Equal(11, testi);
            Assert.Equal("test1", test.MethodWidthParamsString("test"));
            Assert.Equal("12test12", test.MethodWidthParams(12, "test", 12));
        }
예제 #13
0
        public void Test2()
        {
            OopOperator builder = new OopOperator();

            builder
            .Public()
            .Static()
            .Using <OopBuildTest>()
            .Namespace("TestNamespace")
            .Struct()
            .DefinedName("TestExceptionUt2")
            .Body(@"public static void 1 Test(){}")
            .PublicStaticField <string>("Name")
            .PrivateStaticField <int>("_age")
            .Builder();
            var type = builder.GetType();

            Assert.Null(type);
            Assert.Equal(CompileError.Syntax, builder.Compiler.CompileException.ErrorFlag);
            Assert.Equal(CompileError.Syntax, builder.Compiler.SyntaxExceptions[0].ErrorFlag);
        }
예제 #14
0
        static void Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }
            var action = FastMethodOperator.New
                         .MethodBody("return 1+1;")
                         .Return <int>()
                         .Complie <Func <int> >();

            action();

            //FakeMethodOperator.New
            //    .UseMethod<Program>("Main")
            //    .StaticMethodContent($@"Console.WriteLine(""Hello World!"")")
            //    .Complie<Action<string[]>>();

            Console.WriteLine(FakeMethodOperator.New
                              .UseMethod <TestB>("TestMethod")
                              .StaticMethodContent($@"Console.WriteLine(""Hello World!"")")
                              .Builder()
                              );


            /*
             *   在此之前,你需要右键,选择工程文件,在你的.csproj里面
             *
             *   写上这样一句浪漫的话:
             *
             *      <PreserveCompilationContext>true</PreserveCompilationContext>
             */

            OopOperator <TestAbstract> abstractBuilder = new OopOperator <TestAbstract>();

            abstractBuilder.ClassName("UTestClass");
            abstractBuilder["GetName"] = "return Name;";
            abstractBuilder["GetAge"]  = "return Age;";
            abstractBuilder.Compile();
            var test = abstractBuilder.Create("UTestClass");

            var delegate2 = DelegateOperator <GetterDelegate> .Create("return value.ToString();");

            Console.WriteLine(delegate2(1));
            var delegate3     = "return value.ToString();".Create <GetterDelegate>();
            var delegateConvt = FastMethodOperator.New
                                .Param <string>("value")
                                .MethodBody($@"return value==""true"" || value==""mama"";")
                                .Return <bool>()
                                .Complie <Func <string, bool> >();

            Console.WriteLine(delegateConvt("mama"));

            string text = @"using System;
using System.Collections;
using System.Linq;
using System.Text;
 
namespace HelloWorld
{
    public class Test
    {
        public Test(){
            Name=""111"";
            Instance = new Test1();
        }

        public string Name;
        public int Age{get;set;}
        public Test1 Instance;
    }
    public class Test1{
         public string Name=""1"";
    }
}";
            //根据脚本创建动态类
            Type type = RuntimeComplier.GetType(text);
            //创建动态类实例代理
            DynamicOperator instance = new DynamicOperator(type);

            if (instance["Name"].StringValue == "111")
            {
                //调用动态委托赋值
                instance["Name"].StringValue = "222";
            }
            Console.WriteLine("===");
            Console.WriteLine(instance["Instance"].OperatorValue["Name"].StringValue);
            //调用动态类
            Console.WriteLine(instance["Name"].StringValue);

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            if (instance["Name"].StringValue == "111")
            {
                //调用动态委托赋值
                instance["Name"].StringValue = "222";
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);


            var newInstance = DynamicOperator.GetOperator(type);

            stopwatch.Restart();
            if (newInstance["Name"].StringValue == "111")
            {
                //调用动态委托赋值
                newInstance["Name"].StringValue = "222";
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);


            var entity = EntityOperator.Create(type);

            entity.New();
            stopwatch.Restart();
            if (entity["Name"].Get <string>() == "111")
            {
                //调用动态委托赋值
                entity["Name"].Set("222");
            }
            stopwatch.Stop();
            entity.Get("Instance").Set("Name", "haha");
            Console.WriteLine(entity.Get("Instance").Get <string>("Name"));
            Console.WriteLine(stopwatch.Elapsed);

            entity = EntityOperator.Create(type);
            entity.New();
            stopwatch.Restart();
            if (entity["Name"].Get <string>() == "111")
            {
                //调用动态委托赋值
                entity["Name"].Set("222");
            }
            stopwatch.Stop();
            Console.WriteLine("new:" + stopwatch.Elapsed);


            for (int i = 0; i < 10; i++)
            {
                newInstance = DynamicOperator.GetOperator(type);
                stopwatch.Restart();
                if (newInstance["Name"].StringValue == "111")
                {
                    //调用动态委托赋值
                    newInstance["Name"].StringValue = "222";
                }
                stopwatch.Stop();
                Console.WriteLine(stopwatch.Elapsed);
            }



            for (int i = 0; i < 10; i++)
            {
                entity = EntityOperator.Create(type);
                entity.New();
                stopwatch.Restart();
                if (entity["Name"].Get <string>() == "111")
                {
                    //调用动态委托赋值
                    entity["Name"].Set("222");
                }
                stopwatch.Stop();
                Console.WriteLine("new:" + stopwatch.Elapsed);
            }



            for (int i = 0; i < 10; i++)
            {
                newInstance = DynamicOperator.GetOperator(type);
                stopwatch.Restart();
                if (newInstance["Name"].StringValue == "111")
                {
                    //调用动态委托赋值
                    newInstance["Name"].StringValue = "222";
                }
                stopwatch.Stop();
                Console.WriteLine(stopwatch.Elapsed);
            }


            for (int i = 0; i < 10; i++)
            {
                entity = EntityOperator.Create(type);
                entity.New();
                stopwatch.Restart();
                if (entity.Get <string>("Name") == "111")
                {
                    //调用动态委托赋值
                    entity.Set("Name", "222");
                }
                stopwatch.Stop();
                Console.WriteLine("new:" + stopwatch.Elapsed);
            }


            for (int i = 0; i < 10; i++)
            {
                var tEntity = (new TestB()).Caller();
                stopwatch.Restart();
                if (tEntity.Get <string>("Name") == "111")
                {
                    //调用动态委托赋值
                    tEntity.Set("Name", "222");
                }
                stopwatch.Stop();
                Console.WriteLine("new:" + stopwatch.Elapsed);
            }


            //创建动态类实例代理
            DynamicOperator <TestB> instance2 = new DynamicOperator <TestB>();

            if (instance2["Name"].StringValue == "111")
            {
                //调用动态委托赋值
                instance2["Name"].StringValue = "222";
            }
            //调用动态类
            Console.WriteLine(instance2["Name"].StringValue);

            var temp = StaticEntityOperator.Create(typeof(StaticTestB));

            temp.Set("Name", "Name");
            temp.Set("Age", 1);

            Console.WriteLine(temp.Get <string>("Name"));
            Console.WriteLine(temp.Get <int>("Age"));
            Console.WriteLine(StaticTestB.Name);
            Console.WriteLine(StaticTestB.Age);
            Console.ReadKey();
        }
예제 #15
0
        static void Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }
            var action = FastMethodOperator.New
                         .MethodBody("return 1+1;")
                         .Return <int>()
                         .Complie <Func <int> >();

            action();


            FakeMethodOperator.New
            .UseMethod <TestB>("TestMethod")
            .StaticMethodContent($@"Console.WriteLine(""Hello World!"");")
            .Complie <Action>();


            FakeMethodOperator.New
            .UseMethod <TestB>("TestMethod")
            .MethodContent($@"Console.WriteLine(""Hello World!"");")
            .Complie <Action>(new TestA());



            /*
             *   在此之前,你需要右键,选择工程文件,在你的.csproj里面
             *
             *   写上这样一句浪漫的话:
             *
             *      <PreserveCompilationContext>true</PreserveCompilationContext>
             */

            OopOperator <TestAbstract> abstractBuilder = new OopOperator <TestAbstract>();

            abstractBuilder.ClassName("UTestClass");
            abstractBuilder["GetName"] = "return Name;";
            abstractBuilder["GetAge"]  = "return Age;";
            abstractBuilder.Compile();
            var test = abstractBuilder.Create("UTestClass");

            var delegate2 = DelegateOperator <GetterDelegate> .Create("return value.ToString();");

            Console.WriteLine(delegate2(1));
            var delegate3     = "return value.ToString();".Create <GetterDelegate>();
            var delegateConvt = FastMethodOperator.New
                                .Param <string>("value")
                                .MethodBody($@"return value==""true"" || value==""mama"";")
                                .Return <bool>()
                                .Complie <Func <string, bool> >();

            Console.WriteLine(delegateConvt("mama"));

            string text = @"using System;
using System.Collections;
using System.Linq;
using System.Text;
 
namespace HelloWorld
{
    public class Test
    {
        public Test(){
            Name=""111"";
            Instance = new Test1();
        }

        public string Name;
        public int Age{get;set;}
        public Test1 Instance;
    }
    public class Test1{
         public string Name=""1"";
    }
}";
            //根据脚本创建动态类
            Type type = RuntimeComplier.GetClassType(text);



            DynamicMethod method = new DynamicMethod("GetString", null, new Type[] { typeof(TestB), typeof(string) });
            ILGenerator   il     = method.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Stfld, typeof(TestB).GetField("Name"));
            il.Emit(OpCodes.Ret);
            var emitAction = (Action <TestB, string>)(method.CreateDelegate(typeof(Action <TestB, string>)));

            var roslynAction = FastMethodOperator.New
                               .Param <TestB>("instance")
                               .Param <string>("value")
                               .MethodBody("instance.Name = value;")
                               .Return()
                               .Complie <Action <TestB, string> >();


            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Restart();
            for (int i = 0; i < 50000; i++)
            {
                var tEntity = new TestB();
                roslynAction(tEntity, "abc");
            }
            stopwatch.Stop();
            Console.WriteLine("Roslyn:\t" + stopwatch.Elapsed);

            stopwatch.Restart();
            for (int i = 0; i < 50000; i++)
            {
                var tEntity = new TestB();
                emitAction(tEntity, "abc");
            }
            stopwatch.Stop();
            Console.WriteLine("Emit:\t" + stopwatch.Elapsed);


            stopwatch.Restart();
            for (int i = 0; i < 50000; i++)
            {
                var tEntity = new TestB();
                roslynAction(tEntity, "abc");
            }
            stopwatch.Stop();
            Console.WriteLine("Roslyn:\t" + stopwatch.Elapsed);


            stopwatch.Restart();
            for (int i = 0; i < 50000; i++)
            {
                var tEntity = new TestB();
                emitAction(tEntity, "abc");
            }
            stopwatch.Stop();
            Console.WriteLine("Emit:\t" + stopwatch.Elapsed);

            Console.ReadKey();
        }