.Net 3.5 中的 Expression.Assign 的等价物?

发布于 2024-10-09 10:55:35 字数 293 浏览 0 评论 0原文

在.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初雪 2024-10-16 10:55:35

由于您的目标是避免反射的开销,但正在处理表达式树,因此我假设您正在尝试将表达式编译为委托以设置属性。

所有属性都只是幕后的 get 和 set 方法。这些可以被调用 - 这可以在 .NET 3.5 表达式树中使用 Expression.Call 来完成。例如:

class Test{ public int X {get;set;} }

//...elsewhere
var xPropSetter = typeof(Test)
    .GetProperty("X",BindingFlags.Instance|BindingFlags.Public)
    .GetSetMethod();
var newValPar=Expression.Parameter(typeof(int));
var objectPar=Expression.Parameter(typeof(Test));
var callExpr=Expression.Call(objectPar, xPropSetter, newValPar);
var setterAction = (Action<Test,int>)
    Expression.Lambda(callExpr, objectPar, newValPar).Compile();
Test val = new Test();
Console.WriteLine(val.X);//0
setterLambda(val,42);
Console.WriteLine(val.X);//42

请注意,如果您想要的只是一个委托来设置值,您也可以在不使用表达式树的情况下创建委托:

var setterAction = (Action<Test,int>)
    Delegate.CreateDelegate(typeof(Action<Test,int>), xPropSetter);

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:

class Test{ public int X {get;set;} }

//...elsewhere
var xPropSetter = typeof(Test)
    .GetProperty("X",BindingFlags.Instance|BindingFlags.Public)
    .GetSetMethod();
var newValPar=Expression.Parameter(typeof(int));
var objectPar=Expression.Parameter(typeof(Test));
var callExpr=Expression.Call(objectPar, xPropSetter, newValPar);
var setterAction = (Action<Test,int>)
    Expression.Lambda(callExpr, objectPar, newValPar).Compile();
Test val = new Test();
Console.WriteLine(val.X);//0
setterLambda(val,42);
Console.WriteLine(val.X);//42

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:

var setterAction = (Action<Test,int>)
    Delegate.CreateDelegate(typeof(Action<Test,int>), xPropSetter);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文