0
特定の関数(sin(x))から値を取得するメソッドと、代理を使用する関数から値を取得するメソッドを持つクラスがあります。リバースを使用して関数内でdelegateを引数として使用する方法
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;
}
}
私は私のメインでこのクラスを使用します。私はMSDNと、このリソースを読んだ
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();
}
、しかし:私はリフレクションで再びそれを使用したい他のプロジェクトで
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();
}
リフレクションを使用して関数の引数としてデリゲートを使用する方法を理解できません。
なぜあなたは何もしないように、独自の方法を必要とするが、デリゲートを呼び出すのですか?デリゲートを直接呼び出すだけです。 – Servy