I have a specific object in C#, call it MyCustomObject
. MyCustomObject
is of type MyNamespace.CustomObject
, and every object of that type contains a method MyCustomMethod
. I am trying to get the MethodInfo
(System.Reflection.MethodInfo
) of MyCustomObject.MyCustomMethod
so I can use it to create an expression tree later. However, if I just use typeof(MyCustomObject).GetMethod("MyMethodInfo")
, it returns a general method for all objects of type MyNamespace.CustomObject
. How can I get the MethodInfo
of just MyCustomObject.MyCustomMethod
?
When creating your expression tree (per this comment), you presumably want to use the Call
factory method.
In your case, you're trying to create an expression tree representing an instance method call, not a static method call; the difference between them is that an instance method call uses an instance, while a static method call does not.
To create such an expression tree, you'll need some kind of expression tree that represents the instance; it might be a property or field, or the result of another method call. But if you want to apply it to an existing instance, you could pass your instance into the Constant
factory method.
You could pass this node into one of the Call
overloads which represent an instance method call, such as this one, for an instance method call with no arguments.
Something like this:
// using System.Linq.Expressions.Expression
CustomObject MyCustomObject = /* initialized somehow */
var methodInfo = typeof(CustomObject).GetMethod("MyCustomMethod");
var expr = Lambda(
Call(
Constant(MyCustomObject),
methodInfo
),
new ParameterExpression[] { } // if the LambdaExpression has parameters, add them here
);
When using the compiler to generate a similar expression tree:
CustomObject MyCustomObject = /* initialized somehow */
Expression<Action> expr = () => MyCustomObject.MyCustomMethod();
MyCustomObject
isn't represented with a ConstantExpression
, but rather with a MemberAccessExpression
. The C# compiler rewrites closed-over variables (in this case, MyCustomObject
within the lambda expression) as a property access on a compiler-generated object. Instead of the call to Constant
, the corresponding factory methods to represent MyCustomObject
would look something like this:
// using System.Linq.Expressions.Expression
PropertyOrField(
Constant(<<closure_object>>),
"MyCustomObject"
)
We can't write something like this in code, because our code doesn't have access to the <<closure_object>>
instance.