mercredi 30 novembre 2016

How to use delegate as argument in function using reflection C#

I have a class that has method for get value from specific function (sin(x)) and method for get value from any function using 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;
    }

}

I use this class in my main:

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();
    }

In another project I want to use it again with 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();
    }

I have read MSDN and this resource, but coudn't understand how to use delegate as argument in function, using reflection.





Aucun commentaire:

Enregistrer un commentaire