c# - 使用用户定义的名称创建新方法。反射 C#

标签 c# reflection

我想在 RunTime 上创建一个方法。 我希望用户输入一个字符串,该方法的名称将为 DynamicallyDefonedMethod_####(以用户字符串结尾)。

我希望将相同的字符串嵌入到方法的主体中: 它将调用 StaticallyDefinedMethod (####, a, b)

类似于:

public MyClass1 DynamicallyDefonedMethod_#### (int a, int b)
{
return  StaticallyDefinedMethod (####, a, b)
}

想法是用户将在运行时创建一个新方法并在之后调用它(使用 a、b 参数)。

我用谷歌搜索了 C# 反射,但没有找到简单的方法。 有人知道如何简单地做到这一点吗?

问候,

最佳答案

如前所述(评论),更简单的方法就是使用 lambda:

Func<int,int,Whatever> func = (a,b) => StaticallyDefinedMethod(s,a,b);

但您也可以为此使用元编程(如下)。在这里您可以控制方法名称,并且具有更大的灵 active (并不是说您在这里需要它)。但请注意,这并不是真正向类型添加 方法 - 动态方法是独立且断开连接的。您不能真的在运行时向类型添加成员。

using System;
using System.Reflection.Emit;
public class MyClass1  {
    static void Main()
    {
        var foo = CreateMethod("Foo");
        string s = foo(123, 456);
        Console.WriteLine(s);
    }
    static Func<int,int,string> CreateMethod(string s)
    {
        var method = new DynamicMethod("DynamicallyDefonedMethod_" + s,
            typeof(string),
            new Type[] { typeof(int), typeof(int) });
        var il = method.GetILGenerator();
        il.Emit(OpCodes.Ldstr, s);
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.EmitCall(OpCodes.Call, typeof(MyClass1).GetMethod("StaticallyDefinedMethod"), null);
        il.Emit(OpCodes.Ret);
        return (Func<int,int,string>)method.CreateDelegate(typeof(Func<int, int, string>));
    }
    public static string StaticallyDefinedMethod(string s, int a, int b)
    {
        return s + "; " + a + "/" + b;
    }
}

这里最后的想法可能是使用dynamic,但是使用dynamic 很难在运行时选择名称。

关于c# - 使用用户定义的名称创建新方法。反射 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5209368/

相关文章:

Golang 反射 : passing a sturct member variable to a function and return its tag name

java - 使用反射的静态方法

c# - WPF中TabControl的TabChanged事件

c# - 如何查看应用程序的首次安装日期?

c# - 正则表达式匹配和替换数学运算中的运算符

c# - 为什么我在 listView1 上没有属性项?

c# - 使用表达式树而不是反射来获取和设置对象属性

scala - 使用 Scala 2.10 反射查找方法参数(和类型)?

java - 仅使用私有(private)构造函数扩展类

c# - 如何使用 Visual Studio Code 从 .NET Core 访问 Nuget 存储库