mardi 23 juin 2020

how to type to class name in c#

public class FoodA
{
    public static int Eat()
    {
        return 1 ;
    }
    public static int Eat(int a, int b)
    {
        return a+b ;
    }
}

public class FoodB
{
    public static int Eat()
    {
        return 22 ;
    }
    public static int Eat(int a, int b)
    {
        return a*b ;
    }
}

// Is it possible ??
{
    Type tFood = System.Type.GetType("FoodA");
    tFood.Eat()           //  return 1
    tFood.Eat(2, 3)           //  return 5

    tFood = System.Type.GetType("FoodB");
    tFood.Eat()           //  return 22
    tFood.Eat(2, 3)           //  return 6
}

Is there a way to use different class depending on the situation?

        Type type = Type.GetType("FoodA");
        MethodInfo meth = type.GetMethod("Eat") ;
        object ob = Activator.CreateInstance(type,null);
        meth.Invoke(ob, null) ;

The above method is a bit complicated and the function of the same name is not used. Please answer.





Aucun commentaire:

Enregistrer un commentaire