C # call function based on object subtype

I am confused by C # right now.

I have a bunch of classes, say A, B and C, which all come from the Parent class. I have a function that takes an argument of type Parent, and depending on which child class calls the object with which it is called, I want it to call another method.

I am currently thinking of using dictionary matching types for delegates, but that seems silly, although that’s all I can think of for now.

The problem is that when I am in a function, I only know that it is of type Parent, and I can use GetType to get which one I have that will allow the use of a dictionary. Otherwise, I would probably use function overloading.

Indeed, casting seems like the best method that allows me to use function overloading, which would be much less verbose, but I don’t know how I could do it or if it would work at all.

Any recommendations?

+3
source share
4 answers

Overloading is the right way.

public void DoWork(Parent obj)
{
   if(obj is A)
     Foo((A)obj);

   else if(obj is B)
     Foo((B)obj);

   else
    Foo(obj);
}

public void Foo(Parent obj)
{
  //Do something for parent
}

public void Foo(A obj)
{
  //Do something for A
}

public void Foo(B obj)
{
  //Do something for B
}

or if you do not want to explicitly cast an object for each type, you can use reflection as follows:

Bar methodObject = new Bar();
MethodInfo method = methodObject.GetType().GetMethod(
            "Foo", new Type[] { obj.GetType()});

method.Invoke(methodObject, new object[]{obj});
+1
source

Do all methods have the same signature? If so, make it a virtual (potentially abstract) method in the parent class:

using System;

public abstract class Parent
{
    public abstract void DoSomething();
}

public class A : Parent
{
    public override void DoSomething()
    {
        Console.WriteLine("A.DoSomething()");
    }
}

public class B : Parent
{
    public override void DoSomething()
    {
        Console.WriteLine("B.DoSomething()");
    }
}

public class Test
{
    static void Main()
    {
        Parent a = new A();
        Parent b = new B();
        a.DoSomething();
        b.DoSomething();
    }
}

, , ... , - .

+7

This seems like perfect use of the visitor pattern if you cannot add a virtual method to Parent and override it in A, B and C

+2
source

Is the method name different? Or is it another implementation of the same method?

If the method name is the same, you can use an override. In addition, if there ever will be a child method, the parent method should be marked as abstract.

EDIT: with code ...

public abstract class parentClass
{
    //...other stuff...
    protected abstract void doSomething(); //or use virtual instead of abstract and give the method a body
}

public class childClass : parentClass
{
    //...other stuff...
    protected override void doSomething()
    {
       //...do something
    }
}
0
source

Source: https://habr.com/ru/post/1712708/


All Articles