C # dynamic type initializer

I am trying to build something like a C # type initializer dynamically:

MyClass class = new MyClass { MyStringProperty= inputString };

I want to create a generic method that will display one or more instances, and return a delegate that creates a new instance of the class and populates it based on the input parameter. The method signature may look like this:

Func<string,T> CreateFunc<T>();

And calling the resulting function will create a new instance of "T" with (for example) each public property of type String on the value of the argument of the input string.

So, assuming that “MyClass” has only MyStringProperty, the code below will be functionally equivalent to the code at the beginning:

var func = CreateFunc<MyClass>();
func.Invoke(inputString);

System.Reflection System.Linq.Expressions, , , . , .

!

+3
3

, , . , :

public static Func<string, T> CreateFunc<T>()
    where T : class
{
    var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
    var param = Expression.Parameter(typeof(string),"o");
    var constructorInfo = typeof(T).GetConstructor(new Type[] { });
    List<MemberBinding> bindings = new List<MemberBinding>();
    foreach (var property in properties)
        bindings.Add(Expression.Bind(property, param));

    var memberInit = Expression.MemberInit(Expression.New(constructorInfo), bindings);

    var func = Expression.Lambda<Func<string, T>>(memberInit, new ParameterExpression[] {param}).Compile();

    return func;            
}
+1

CLR 4.0 .

. - # StringBuilder, . .

IL Reflection Emit , .

+1

, , , vodoo, .

, . , . , , .

, ? ?

0

Source: https://habr.com/ru/post/1733579/


All Articles