开发者

setting private properties of classes

开发者 https://www.devze.com 2023-02-14 16:17 出处:网络
I have some very old code which uses reflection to set properties of objects, e.g something like this:

I have some very old code which uses reflection to set properties of objects, e.g 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 about replacing that code to make it fa开发者_StackOverflow社区ster. But because the above code also allows setting private properties of an object, I'm not sure what other options there exist.

Questions:

  1. Am I correct, that compiled expressions (using System.Linq.Expressions) and generated code (using CodeDom / Microsoft.CSharp.CSharpCodeProvider) cannot be used to set private properties?
  2. Would that be possible using Reflection.Emit?
  3. Would any of the mapping libraries (AutoMapper, ValueInjecter) help for this (I don't know what technology they use internally)?
  4. Are there other options?


The open source framework Impromptu-Interface has a static method InvokeSet uses the DLR rather than reflection, and it will call private methods. It runs a little over 2 times faster than reflection in the unit speed test case, which looks similar to yours.

using ImpromptuInterface;

...

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

精彩评论

暂无评论...
验证码 换一张
取 消