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:
- 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?
- Would that be possible using Reflection.Emit?
- Would any of the mapping libraries (AutoMapper, ValueInjecter) help for this (I don't know what technology they use internally)?
- 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]);
}
精彩评论