简体   繁体   English

如何创建表达式 <Action> 在.NET中给出了完全合格的类名和方法名?

[英]How do I create an Expression<Action> given a fully-qualified class name and a method name in .NET?

I need to create an Expression<Action> that represents calling a method on a class. 我需要创建一个Expression<Action>来表示在类上调用方法。

As input, I have a string that describes the assembly and class name (standard fully-qualified class name) and another string that defines the method to invoke. 作为输入,我有一个描述程序集和类名(标准的完全合格的类名)的字符串,以及另一个定义要调用的方法的字符串。

The class/method to be invoked are NOT actually available in the code where the Expression has to be created, so I can't just write ()=>MyClass.Invoke(); 必须在创建表达式的代码中实际上没有要调用的类/方法,所以我不能只写()=>MyClass.Invoke(); -- I don't have MyClass 's assembly as a reference. -我没有MyClass的程序集作为参考。

System.Action act = () =>
{
    var typeName = "";
    var methodName = "";

    var type = System.Type.GetType(typeName);
    var method = type.GetMethod(methodName);

    object[] constructorArgs = null;
    var obj = type.InvokeMember(null,  System.Reflection.BindingFlags.CreateInstance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, constructorArgs);

    object [] methodArgs = null;
    method.Invoke(obj, methodArgs);
};
System.Linq.Expressions.Expression<System.Action> exp = () => act();
exp.Compile()();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM