Created
February 4, 2012 07:29
-
-
Save adjames/1736161 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 hidden or 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@adjames, it seems that the statement
return New<TResult,string>(name);
should have the generics the other way round:return New<string, TResult>(name);