Creating method dynamically, and executing it

后端 未结 6 1200
轮回少年
轮回少年 2020-12-23 22:42

Background:

I want to define few static methods in C# , and generate IL code as byte array, from one of these methods, selected at runt

6条回答
  •  一个人的身影
    2020-12-23 23:46

    This answer is a wee bit orthogonal - more about the problem than the technology involved.

    You could use expression trees - they're nice to work with and have VS syntactic sugar.

    For serialization you need this library (you'll need to compile it too): http://expressiontree.codeplex.com/ (This works with Silverlight 4 too, apparently.)

    The limitation of expression trees is that they only support Lambda expressions - i.e. no blocks.

    This isn't really a limitation because you can still define other lambda methods within a lambda and pass them to functional-programming helpers such as the Linq API.

    I've included a simple extension method to show you how to go about adding other helper methods for functional stuff - the key point is that you need to include the assemblies containing the extensions in your serializer.

    This code works:

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using ExpressionSerialization;
    using System.Xml.Linq;
    using System.Collections.Generic;
    using System.Reflection;
    
    namespace ExpressionSerializationTest
    {
        public static class FunctionalExtensions
        {
            public static IEnumerable to(this int start, int end)
            {
                for (; start <= end; start++)
                    yield return start;
            }
        }
    
        class Program
        {
            private static Expression> sumRange = 
                (x, y) => x.to(y).Sum();
    
            static void Main(string[] args)
            {
                const string fileName = "sumRange.bin";
    
                ExpressionSerializer serializer = new ExpressionSerializer(
                    new TypeResolver(new[] { Assembly.GetExecutingAssembly() })
                );
    
                serializer.Serialize(sumRange).Save(fileName);
    
                Expression> deserializedSumRange =
                    serializer.Deserialize>(
                        XElement.Load(fileName)
                    );
    
                Func funcSumRange = 
                    deserializedSumRange.Compile();
    
                Console.WriteLine(
                    "Deserialized func returned: {0}", 
                    funcSumRange(1, 4)
                );
    
                Console.ReadKey();
            }
        }
    }
    

提交回复
热议问题