Created
July 30, 2021 21:23
-
-
Save SteveDunn/671cffb177ad9793fa0e37568efef39a to your computer and use it in GitHub Desktop.
Workaround for inability to create C# generic constraints for the presence of a constructor that takes parameters... i.e. Foo<T>(string name) where T: new(string)
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 Func<T1, TResult> CompileConstructor<T1, TResult>() | |
{ | |
var type1 = typeof(T1); | |
var parameter1 = Expression.Parameter(type1); | |
var constructor = typeof(TResult).GetConstructor(new Type[] { type1 }); | |
var body = Expression.New(constructor, parameter1); | |
var lambda = Expression.Lambda<Func<T1, TResult>>(body, parameter1); | |
var method = lambda.Compile(); | |
return method; | |
} | |
// obviously you could do some caching here... | |
public TResult New<T1, TResult>(T1 t1) | |
{ | |
return GetConstructor<T1, TResult>()(t1); | |
} | |
// example usage: i.e. a generic method that calls an unnamed type constructor that takes a parameter (in this case a string). | |
public TResult CreateNode<TResult>(string name) where TResult: INode | |
{ | |
return New<TResult,string>(name); | |
} | |
// copied line by line from https://gist.github.com/adjames/1736161 - in case it goes and I can't remember how to do it! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment