lundi 3 décembre 2018

C# Dynamic delegate for getter and setter of dynaimally created class using reflection

I am using this .Net reflection code to generate a dynamic class instances at runtime.

https://www.c-sharpcorner.com/UploadFile/87b416/dynamically-create-a-class-at-runtime/

I am using .Net reflections to create list of objects with dynamic set of properties since I am reading input from excel file which may have dynamic columns as per the business requirement. But I am doing lot of loops to get the GetType().GetProperty("") which is reducing the performance. I am trying to delegate it dynamically for the propertiesinfo[] which I get from the GetType().GetProperties().

Below is a static getter and settter delegate for Property1 of the runtime class created.

Action<MyClass, int> setter = (Action<MyClass, int>)Delegate.CreateDelegate(typeof(Action<MyClass, int>), null, typeof(MyClass).GetProperty("Property1").GetSetMethod());  

Func<MyClass, int> getter = (Func<MyClass, int>)Delegate.CreateDelegate(typeof(Func<MyClass, int>), null, typeof(MyClass).GetProperty("Property1").GetGetMethod());

I would like to make this dynamic for each property created of my class. I'm stuck and not sure whether I can use any Linq MemberExpression to achieve it.

Can anyone help me out? That would be great.





Aucun commentaire:

Enregistrer un commentaire