Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取C中变量下函数的MethodInfo#_C#_Lambda_Expression_Expression Trees_Methodinfo - Fatal编程技术网

C# 获取C中变量下函数的MethodInfo#

C# 获取C中变量下函数的MethodInfo#,c#,lambda,expression,expression-trees,methodinfo,C#,Lambda,Expression,Expression Trees,Methodinfo,我在C#中有一个特定的对象,称之为MyCustomObjectMyCustomObject属于MyNamespace.CustomObject类型,并且该类型的每个对象都包含一个方法MyCustomMethod。我正在尝试获取MyCustomObject.MyCustomMethod的MethodInfo(System.Reflection.MethodInfo),以便稍后使用它创建表达式树。但是,如果我只使用typeof(MyCustomObject).GetMethod(“MyMethodI

我在C#中有一个特定的对象,称之为
MyCustomObject
MyCustomObject
属于
MyNamespace.CustomObject
类型,并且该类型的每个对象都包含一个方法
MyCustomMethod
。我正在尝试获取
MyCustomObject.MyCustomMethod
MethodInfo
System.Reflection.MethodInfo
),以便稍后使用它创建表达式树。但是,如果我只使用
typeof(MyCustomObject).GetMethod(“MyMethodInfo”)
,它将为类型为
MyNamespace.CustomObject
的所有对象返回一个通用方法。如何获得MyCustomObject.MyCustomMethod的
MethodInfo

在创建表达式树(per)时,您可能希望使用factory方法

在您的例子中,您试图创建一个表达式树,表示一个实例方法调用,而不是一个静态方法调用;它们之间的区别在于实例方法调用使用实例,而静态方法调用不使用实例

要创建这样的表达式树,您需要某种表示实例的表达式树;它可能是一个属性或字段,或者是另一个方法调用的结果。但是,如果要将其应用于现有实例,可以将实例传递到
常量
工厂方法中

您可以将此节点传递到一个表示实例方法调用的
Call
重载中,例如不带参数的实例方法调用

大概是这样的:

// using System.Linq.Expressions.Expression

PropertyOrField(
    Constant(<<closure_object>>),
    "MyCustomObject"
)
//使用System.Linq.Expressions.Expression
CustomObject MyCustomObject=/*已初始化*/
var methodInfo=typeof(CustomObject).GetMethod(“MyCustomMethod”);
var expr=Lambda(
召唤(
常量(MyCustomObject),
方法信息
),
新ParameterExpression[]{}//如果LambdaExpression有参数,请将它们添加到此处
);

补遗 使用编译器生成类似的表达式树时:

CustomObject MyCustomObject = /* initialized somehow */
Expression<Action> expr = () => MyCustomObject.MyCustomMethod();

我们不能在代码中编写这样的东西,因为我们的代码没有访问
实例的权限。

没有这样的东西。方法存在于类中,而不是类的实例中。你得到了
MethodInfo
Invoke
它传递了你想要的实例。这个问题对我来说没有多大意义。我怀疑OP只需要使用
myInstance.GetType()
而不是
typeof(MyCustomObject)
。我想做的是构造一个调用
MyCustomObject.MyCustomMethod
的表达式树,我使用了
expression.Call
,但我需要
MethodInfo
。如何构造表达式树来调用
MyCustomObject.MyCustomMethod
?@4yl1n您所做的就是这样。这就是您需要在该类型上调用该方法的methodinfo。对于对象的特定实例,没有所谓的
methodinfo
。想一想在不使用反射的情况下,您将如何/什么样的代码用C#编写,并在文章中解释您正在尝试做什么。