我想在 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/