我有一个类,它具有从特定函数(sin(x))获取值的方法以及使用委托从任何函数获取值的方法。
namespace ValueFunctionFinder {
public delegate double SomeFunction(double arg);
public class ValueFunctionFinderClass
{
public double GetValue(double x)
{
double y = Math.Sin(x);
return y;
}
public double GetValueDel(double x, SomeFunction function)
{
double y = function(x);
return y;
}
}
我在我的主要课程中使用这个课程:
static void Main(string[] args)
{
ValueFunctionFinderClass finder = new ValueFunctionFinderClass();
double x = Math.Sin(Math.PI / 6);
// find value from specific function
double y = finder.GetValue(x);
Console.WriteLine($"Sin(PI/6) = {y}");
// find value from any function
SomeFunction function = Math.Sin;
y = finder.GetValueDel(x, function);
Console.WriteLine($"Sin(PI/6) = {y}");
Console.ReadLine();
}
在另一个项目中,我想再次使用Reflection:
static void Main(string[] args)
{
Assembly assembly = Assembly.Load("ValueFunctionFinder");
Type functionFinderType = assembly.GetType("ValueFunctionFinder.ValueFunctionFinderClass");
object functionFinderObj = Activator.CreateInstance(functionFinderType);
// find value from specific function using Reflection
MethodInfo getValueMethodInfo = functionFinderType.GetMethod("GetValue");
double x = Math.Sin(Math.PI / 6);
object y = getValueMethodInfo.Invoke(functionFinderObj, new object[] { x });
Console.WriteLine($"Sin(PI/6) = {y}"); // it works OK
// find value from any function with Reflection
Type someFunctionType = assembly.GetType("ValueFunctionFinder.SomeFunction");
// I should use smth like this:
// **********************************************
// dynamic creation of delegate
//Delegate del = Delegate.CreateDelegate(someFunctionType, someMethodInfo); // what kind of methodInfo shoul I use?
// dynamic use of delegate
//object function = del.DynamicInvoke(arguments); // what kind of arguments? Math.Sin?
// **********************************************
MethodInfo getValueDelMethodInfo = functionFinderType.GetMethod("GetValueDel");
//y = getValueDelMethodInfo.Invoke(functionFinderObj, new object[] {x, function});
Console.WriteLine($"Sin(PI/6) = {y}"); // how do this?
Console.ReadLine();
}
我已经阅读了MSDN和这个资源,但是不能理解如何在函数中使用委托作为参数,使用反射。
答案 0 :(得分:0)
SomeFunction function = Math.Sin;
是
的快捷方式SomeFunction function = new SomeFunction(Math.Sin);
并且反射可以通过MethodInfo.CreateDelegate method:
为我们完成此操作var getValueDelMethod = functionFinderType.GetMethod("GetValueDel");
// create a delegate to the target method of the desired type
var delegateType = typeof(SomeFunction);
var sinMethod = typeof(Math).GetMethod(nameof(Math.Sin));
var delegateObj = sinMethod.CreateDelegate(delegateType);
var result = getValueDelMethod.Invoke(functionFinderObj, new object[] {x, delegateObj});