Click to See Complete Forum and Search --> : How to create an assignment expression and evaluate it at runtime?


CoDavid
March 12th, 2008, 01:14 AM
Hi,



In my case, I have an "op_Equality" expression, and I want to create an assignment expression base on it. I want to assign the value on the right of the "op_Equality" expression to a member of some object.



Could someone give a sample? I am new on this...thx!

DeepT
March 12th, 2008, 02:21 PM
I do not understand your question. Perhaps some sudo-code might help clarify it.

CoDavid
March 12th, 2008, 08:13 PM
Thanks. Here's the code snippet.


MemberExpression me = ((MemberExpression)b.Left);
Type t = me.Expression.Type;
ParameterExpression pe = (ParameterExpression)me.Expression;
string strMemberName = me.Member.Name;
MethodInfo methodInfo = t.GetProperty(strMemberName).GetSetMethod();



I have a BinaryExpression (b), it's left member is a MemberAccessExpression to which I want to assign a value it's right member is a ConstantExpression of which I want to assign.

What I want to do is to create a CallExpression to to the SetValue method of the member to assign the value (b.right) to it.

riscutiavlad
March 13th, 2008, 02:24 AM
You can do this using Reflection. To assign a value to a field of an instance of a class, get the field using the GetField method provided by the Type class. Or you can use the GetProperty method to get a property.
Reflection provides the FieldInfo class for fields and the PropertyInfo class for properties, both providing the method SetValue.

For example:

public void SetField(object instance, string field, object value)
{
FieldInfo fi = instance.GetType().GetField(field);

fi.SetValue(instance, value);
}

This will assign the value object to the field named field of the instance object. You can do almost anything with Reflection, from my experience, the only thing you can not do is to retrieve current instances of classes. That means that you have to keep track of the instance object above somewhere - you should create it and store it somewhere.

Keep in mind that Reflection operations are costly so if you want performance, you should try something else.

boudino
March 13th, 2008, 03:15 AM
Look at RunSharp (http://www.codeproject.com/KB/dotnet/runsharp.aspx).

CoDavid
March 14th, 2008, 08:07 AM
Thx!
:)