Setting private class properties

I have very old code that uses reflection to set properties of objects, for example, something like this:

var properties = obj.GetType().GetProperties(
  BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in properties)
{
  property.SetValue(obj, lookup[property.Name]);
}

I was thinking of replacing this code to make it faster. But since the above code also allows you to set the private properties of an object, I'm not sure what other options exist.

Questions:

  • Is it true that compiled expressions (using System.Linq.Expressions) and generated code (using CodeDom / Microsoft.CSharp.CSharpCodeProvider) cannot be used to set private properties?
  • Can I use Reflection.Emit?
  • Will any of the mapping libraries ( AutoMapper , ValueInjecter ) help for this (I don't know what technology they use internally)?
  • ?
+3
1

Impromptu-Interface InvokeSet DLR, , . 2 , , .

using ImpromptuInterface;

...

foreach(var property in properties){
    ImpromptuInterface.InvokeSet(obj, property.Name, lookup[property.Name]);
}
+1

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


All Articles