我有以下类层次结构:
public class Parent
{
[DebuggerStepThrough]
public void SayParent()
{
Console.WriteLine("Parent");
}
}
public sealed class Child : Parent
{
private static int _number = 0;
public Child() // May contain parameter i.e. not always parameterless consctructor
{
_number++;
}
[DebuggerStepThrough]
public void SayInstance()
{
Console.WriteLine("{0}-Say", _number);
}
[DebuggerStepThrough]
public void SayInstanceWithArg(string input)
{
Console.WriteLine("{0}-Say: {1}", _number, input);
}
[DebuggerStepThrough]
public static void SayStatic()
{
Console.WriteLine("{0}-Say", _number);
}
[DebuggerStepThrough]
public static void SayStaticWithArg(string input)
{
Console.WriteLine("{0}-Say: {1}", _number, input);
}
[DebuggerStepThrough]
public static Task SayStaticWithArgAndReturn(string input)
{
Console.WriteLine("{0}-Say: {1}", _number, input);
return null;
}
}
我需要能够使用反射在任何时候为一个新的
Child
实例调用这些方法,然而为了提高性能,我需要采用Delegate
和/或Compiled Expressions
。
例如,我可以有:
var instanceOne = new Child();
var instanceTwo = new Child();
我需要在运行时调用这些方法,并传递需要的参数。请注意,它们包括既有 静态
方法,也有 实例
方法,其中一些接受参数。
到目前为止,我已经尝试了以下内容来调用 "SayInstance" 方法:
var sayInstanceMethod = typeof(Child)
.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
.Where(m => m.GetCustomAttributes(typeof(DebuggerStepThroughAttribute), true).Length > 0)
.Where(t => t.Name == "SayInstance")
.First()
然后:
var instance = Expression.Constant(new Child()); // This should NOT be Constant, but then what should it be?!
var mCallInstance = Expression.Call(instance, sayInstanceMethod);
Action action = Expression.Lambda<Action>(mCallInstance).Compile();
action();
action(); // I need to pass in a new instance of Child to this method somehow
然而我得到:
1-Say
1-Say
代替:
1-Say
2-Say
我怀疑这是由于
Expression.Constant
引起的,但我无法弄清楚如何让它在运行时接受Child
实例作为其目标。当涉及到
Expressions
时,我感到无助 :-(基本上,我正在尝试实现Jon Skeet在这里提到的内容,使用
Delegates
或Compiled Expressions
。非常感谢任何帮助。
Child
新实例的表达式。 - MaYaNaction();
的同一个测试中,是否运行了var instanceOne = new Child();
和var instanceTwo = new Child();
这两行代码? - Mataction()
之间,难道不应该创建一个新的instance
、mCallInstance
和action
来获取第二个实例,从而增加你的静态整数吗? - Mikanikal