Some fun with private ctors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Factory<T> where T : class | |
{ | |
private static readonly Func<T> FactoryFn; | |
static Factory() | |
{ | |
//FactoryFn = CreateUsingActivator(); | |
FactoryFn = CreateUsingLambdas(); | |
} | |
private static Func<T> CreateUsingActivator() | |
{ | |
var type = typeof(T); | |
Func<T> f = () => Activator.CreateInstance(type, true) as T; | |
return f; | |
} | |
private static Func<T> CreateUsingLambdas() | |
{ | |
var type = typeof(T); | |
var ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.NonPublic, null, new Type[] { }, null); | |
var ctorExpression = Expression.New(ctor); | |
return Expression.Lambda<Func<T>>(ctorExpression).Compile(); | |
} | |
public static T Create(Action<T> init) | |
{ | |
var instance = FactoryFn(); | |
init(instance); | |
return instance; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IPerson | |
{ | |
string Name { get; set; } | |
} | |
public class Person : IPerson | |
{ | |
public string Name { get; set; } | |
private Person() { } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//TOUCH ONCE BEFORE TIMING | |
var touchedPerson = Factory<Person>.Create(p => p.Name = "Daniel"); | |
for (var a = 0; a < 5; a++) | |
{ | |
var sw = Stopwatch.StartNew(); | |
for (int c = 0; c < 100000; c++) | |
{ | |
var person = Factory<Person>.Create(p => p.Name = "Daniel"); | |
var n = person.Name; | |
} | |
sw.Stop(); | |
Console.WriteLine(sw.Elapsed.TotalMilliseconds); | |
} | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment