.Net 3.5 中的 Expression.Assign 的等价物?
在.Net 4.0中,微软添加了Expression.Assign。不过我还是坚持使用 3.5。我正在尝试想出一些方法来编写可以设置对象属性的方法,但到目前为止我还没有太多运气。我可以这样做:
public void Assign(object instance, PropertyInfo pi, object value)
{
pi.SetValue(instance, value, null);
}
但我想避免使用反射的开销!属性不能与ref
一起使用。这可能吗?
In .Net 4.0 Microsoft added Expression.Assign. I'm stuck with using 3.5, though. I'm trying to come up with some means of write a method that can set the object property, but so far I haven't had much luck. I can do this:
public void Assign(object instance, PropertyInfo pi, object value)
{
pi.SetValue(instance, value, null);
}
But I want to avoid the overhead of using reflection! Properties cannot be used with a ref
. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您的目标是避免反射的开销,但正在处理表达式树,因此我假设您正在尝试将表达式编译为委托以设置属性。
所有属性都只是幕后的 get 和 set 方法。这些可以被调用 - 这可以在 .NET 3.5 表达式树中使用
Expression.Call
来完成。例如:请注意,如果您想要的只是一个委托来设置值,您也可以在不使用表达式树的情况下创建委托:
Since you're aiming to avoid the overhead of reflection but are dealing with expression trees, I'm assuming you're trying to compile an expression to a delegate to set a property.
All properties are simply get and set methods behind the scenes. These can be called - and this can be done in .NET 3.5 expression trees using
Expression.Call
. For instance:Note that if all you want is a delegate to set a value, you can also create the delegate without using an expression tree at all: