I have a number properties on a class that follow a particular convention. Eg.
Person1 { get; set; }
Person2 { get; set; }
Person3 { get; set; }
I don't want to have to get a MethodInfo
object on the instance of the class, but do something like this instead:
...
il.Emit(OpCodes.Callvirt, [instance]["set_Person" + index]);
The above line of code is illustrative and not what I think it should be.
Does anyone know how I can get around to do this?
It can't be done and I don't understand the point or any potential benefit. The MSIL Callvirt instruction does not take a string describing what to call, it takes a metadata token which points to a specific method on a specific type, and the only way to get that value via reflection is with a MethodInfo instance.
This really doesn't seem like a complicated alternative:
il.Emit(OpCodes.Callvirt, type.GetMethod("set_Person" + index));
public class Sample
{
public int Person1 { get; set; }
public int Person2 { get; set; }
public int Person3 { get; set; }
}
static void Main(string[] args) {
var s = new Sample();
var tuples = new List<Tuple<string, int>> {
Tuple.Create("Person1", 1),
Tuple.Create("Person2", 2),
Tuple.Create("Person3", 3)
};
var argument = Expression.Constant(s);
foreach (var item in tuples) {
CreateLambda(item.Item1, argument, item.Item2)
.Compile()
.DynamicInvoke();
}
}
static LambdaExpression CreateLambda(string propertyName, Expression instance, int value) {
return Expression.Lambda(
Expression.Assign(
Expression.PropertyOrField(instance, propertyName),
Expression.Constant(value)));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.