Skip to content

Instantly share code, notes, and snippets.

@sakapon
Last active October 3, 2015 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakapon/3eef764cc3fc94ef5de0 to your computer and use it in GitHub Desktop.
Save sakapon/3eef764cc3fc94ef5de0 to your computer and use it in GitHub Desktop.
ExpressionsSample / EntityType (Lambda)
using System;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace ExpressionsConsole
{
[DebuggerDisplay(@"{typeof(TEntity)}")]
public class EntityType<TEntity>
{
public ConstructorInfo ConstructorInfo { get; private set; }
Func<object[], TEntity> _constructor;
internal EntityType(ConstructorInfo constructorInfo)
{
ConstructorInfo = constructorInfo;
_constructor = CompileConstructor(constructorInfo);
}
public TEntity CreateEntity(params object[] parameters)
{
return _constructor(parameters);
}
static Func<object[], TEntity> CompileConstructor(ConstructorInfo constructorInfo)
{
var parameterInfoes = constructorInfo.GetParameters();
var p = Expression.Parameter(typeof(object[]), "p");
var ctorExp = Expression.New(constructorInfo, parameterInfoes.Select(i => GetParameterValue(p, i)));
// p => new TEntity((int)p[0], (string)p[1])
var ctorLambda = Expression.Lambda<Func<object[], TEntity>>(ctorExp, p);
return ctorLambda.Compile();
}
static Expression GetParameterValue(ParameterExpression p, ParameterInfo info)
{
var p_i = Expression.ArrayIndex(p, Expression.Constant(info.Position));
return Expression.Convert(p_i, info.ParameterType);
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExpressionsConsole
{
class Program
{
static void Main(string[] args)
{
EntityTypeTimeTest();
}
static void EntityTypeTimeTest()
{
var sw = Stopwatch.StartNew();
var PersonType = EntityType.Create(new { Id = 0, Name = "", Birthday = DateTime.MinValue });
Console.WriteLine(sw.Elapsed);
for (var i = 0; i < 1000000; i++)
PersonType.CreateEntity(i, "Person", DateTime.MaxValue);
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment