设置类的私有属性
我有一些非常旧的代码,它们使用反射来设置对象的属性,例如:
var properties = obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in properties)
{
property.SetValue(obj, lookup[property.Name]);
}
我正在考虑替换该代码以使其更快。但因为上面的代码还允许设置对象的私有属性,所以我不确定还存在哪些其他选项。
问题:
- 我是否正确,编译的表达式(使用 System.Linq.Expressions)和生成的代码(使用 CodeDom / Microsoft.CSharp.CSharpCodeProvider)不能用于设置私有属性?
- 使用 Reflection.Emit 可以吗?
- 任何映射库(AutoMapper、ValueInjecter) 对此有帮助吗(我不知道他们内部使用什么技术)?
- 还有其他选择吗?
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 faster. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
开源框架 Impromptu-Interface 有一个静态方法
InvokeSet
使用 DLR 而不是反射,并且它将调用私有方法。在单位速度测试用例中,它的运行速度比反射快 2 倍多一点,这看起来与您的类似。...
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....