How can I call a method on an instance using MSIL * without * having MethodInfo?

I have numerical properties for a class that follow a specific convention. For instance.

Person1 { get; set; } Person2 { get; set; } Person3 { get; set; } 

I don't want to get a MethodInfo object in an instance of the class, but instead do something like this:

 ... il.Emit(OpCodes.Callvirt, [instance]["set_Person" + index]); 

The above line of code is illustrative, not the one I think should be.

Does anyone know how I can get around this?

+4
source share
2 answers

This is impossible to do, and I do not understand the meaning or potential benefits. The MSIL Callvirt instruction does not take a line describing what needs to be called, it takes a metadata token that points to a specific method of a particular type, and the only way to get this value through reflection is with an instance of MethodInfo.

This really doesn't seem like a complicated alternative:

 il.Emit(OpCodes.Callvirt, type.GetMethod("set_Person" + index)); 
+1
source
 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))); } 
0
source

Source: https://habr.com/ru/post/1436767/


All Articles