Instantiating Immutable Objects With Reflection

前端 未结 3 1702
我寻月下人不归
我寻月下人不归 2021-02-10 08:03

I created a base class to help me reduce boilerplate code of the initialization of the immutable Objects in C#,

I\'m using lazy initialization in order to try not to imp

3条回答
  •  不思量自难忘°
    2021-02-10 08:13

    My favourite way to things like that is to use expression trees. You can manually construct your expression tree to just create a new instance of your type and compile this expression tree into a delegate. The beauty of this approach is that you only need reflection and dynamic code generation for once and afterwards you work with the generated delegate. Also, the expression compiler does its best to work even on partial trusted environments, where dynamic methods are problematic. On the other hand, you have an abstraction layer much higher than writing pure IL code in an ILGenerator, which would be the way to go in a dynamic method.

提交回复
热议问题