What's the easiest way to generate code dynamically in .NET 4.5?

前端 未结 4 1128
旧时难觅i
旧时难觅i 2020-12-31 23:41

I\'m writing a specific kind of object-mapper. Basically I want to convert from a DataTable that has the fields a, b and c

4条回答
  •  情歌与酒
    2021-01-01 00:17

    I wouldn't be so quick to dismiss expressions. You can use expressions in one of several different ways to accomplish your goal.

    1. If you are using .NET 4+, you the expression trees have been extended to support blocks of code. While you can't use this functionality with the lambda syntactic sugar, you can use the Expression.Block method to create a code block.

    2. Use a constructor that has a parameter for each field you are mapping. The generated code could mimic return new T(ExtractA(t), ExtractB(t), ...). In this case you would remove the where T : new() constraint from Map and instead rely on your object model classes having a constructor that can be found using reflection with a parameter for each mapped property.

    3. Use helper methods to execute a series of statements as if it were a single statement. The generated code could mimic return ApplyProperties(t, new T(), new[] { applyA, applyB, ... }), where applyA and applyB are Action delegates that were separately compiled from expressions designed to set a single specific property. The ApplyProperties method is a helper method in your code like the following:

       private T ApplyProperties(DataTable t, T result, Action[] setters)
       {
           foreach (var action in setters)
           {
               action(t, result);
           }
      
           return result;
       }
      

提交回复
热议问题