Calling C # methods dynamically based on data from a database

My boss asked me to look into the computing engine. In fact, the user will have a data table in which calculations can be performed. They will also be able to build their own calculations based on certain restrictions that we apply (built-in calculations will then be stored in the database).

Is it possible to call a specific method in C #, depending on what is stored in the database? Therefore, if the database says, the calculation should perform the standard deviation. When we get this information from the database, is it possible then to call the standard rejection method that we will have in C #?

Hope this is clear.

+5
source share
6

/ , , , . / switch. , .

, , , . , . , , . MethodInfo.Invoke() .

, Invoke() , , MethodInfo . . .

, , 1 - .

+3

, ; , #. ; :

using System;
using System.Reflection;

class CallMethodByName
{
   string name;

   CallMethodByName (string name)
   {
      this.name = name;
   }

   public void DisplayName()      // method to call by name
   {
      Console.WriteLine (name);   // prove we called it
   }

   static void Main()
   {
      // Instantiate this class
      CallMethodByName cmbn = new CallMethodByName ("CSO");

      // Get the desired method by name: DisplayName
      MethodInfo methodInfo = 
         typeof (CallMethodByName).GetMethod ("DisplayName");

      // Use the instance to call the method without arguments
      methodInfo.Invoke (cmbn, null);
   }
}

http://en.csharp-online.net/CSharp_FAQ:_How_call_a_method_using_a_name_string

+2

switch # ( ), . , , reflection MethodInfo member "string name" .

0

, Reflection. , , , .

public static class UserOperations
{
    public static decimal Average(IEnumerable<decimal> source)
    {
        return source.Average();
    }

    // Other methods
}


class Program
{
    static void Main(string[] args)
    {
        // The operation retrieved from the db
        string operation = "Average";
        // The items on which the operations should be performed
        decimal[] items = { 22m, 55m, 77m };

        object result = typeof(UserOperations).GetMethod(operation).Invoke(null, new object[] { items });
        Console.WriteLine(result);
        Console.ReadLine();
    }
}
0

All Articles