E
E
e1s2015-10-19 20:06:22
C++ / C#
e1s, 2015-10-19 20:06:22

How to call class methods with parameters from xml file or array?

There is a class with methods that can take string variables as parameters, while the methods are different both in the number of parameters they take and in the return value. For example

obj["param1"] = xmlobj.SelectSingleNode["param2", nsmg].Atribute["param3"].Value;
obj["param4"] = class_method("param5");

There is an xml file that stores these parameters, for simplicity, let's take an array
string[,] param_mas = 
{
{"param1", "param2", "param3"},
{....},
}

How can this array store / pass a parameter that will be responsible for which method to use for a given set of parameters?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artyom, 2015-10-19
@e1s

Organize in your code some structure / class in which you will store the name of the called method and its parameters. for example

public class SampleContainer
    {
        public string MethodName { get; set; }
        public object[] Params { get; set; }
    }

In XML it might look something like this:
<Method>
    <Name>Some_Method_Name</Name>
    <Params>
      <Param name = 'param1' value='value1'></Param>
      <Param name = 'param2' value='value2'></Param>
    </Params>
</Method>

Next, parse XML in the code, save it to your structure and call the method you need through Reflections, example:
using System;
using System.Reflection;
namespace ConsoleApplication2
{
    public class Sample
    {
        public string SampleMethod(string param1, string param2)
        {
            return param1 + param2;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Sample sample = new Sample();
            var method = typeof(Sample).GetMethod("SampleMethod");
            object[] param = new object[] {"Hello ","World!"};
            string result = method.Invoke(sample, param) as string;
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

A
AtomKrieg, 2015-10-19
@AtomKrieg

{method = "method1", param1", "param2", "param3"}
Well, then call method by name, a dictionary of functors or case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question