Home > Back-end >  How to define a method in abstract class with different classes as input parameter?
How to define a method in abstract class with different classes as input parameter?

Time:05-12

I have an abstract class which looks like this for example:

public abstract class CPD 
{
     public double[,] Func(double[] data, double value, SomeClass item) 
     {
         // Some code
     }

     public abstract double[] Fun1(double x);
     public abstract void Fun2(double x);
    
}

And I also have 3 different classes, with different constructors, functions, and etc. I wanted to define somehow my method "Func" which is in code, to be able to use as an input parameter (instead of "SomeClass") one of those 3 different classes I have.

So, whenever I call some of those 3 classes, I can override the methods "Fun1" and "Fun2", but I can use always in either of those 3 classes the Method "Func".

How could I do that?

CodePudding user response:

If you want to use just one class instead of three classes, you can create a base class or interface and put the same behaviour into this newly created abstract class. And then just call it in your Func method.

For example, we can create an abstract class Display:

public abstract class Display 
{
    public abstract string Show();
}

And then it is necessary to create concrete implementations of this base class Display:

public class SamsungDisplay : Display
{
    public override string Show()
    {
        return "I am Samsung";
    }
}

public abstract class SonyDisplay : Display
{
    public override string Show()
    {
        return "I am Sony";
    }
}

public abstract class DellDisplay : Display
{
    public override string Show()
    {
        return "I am Dell";
    }
}

and then we can use any derived class instead of base class:

// Here you can pass SamsungDisplay, SonyDisplay or DellDisplay 
public void UseDisplay(Display display) 
{
    display.Show();
}

CodePudding user response:

As others have said, you can use interfaces or a common base class to accomplish this. But for completeness: you can also use a generic:

public class SomeClass
{
    private static readonly Random Random = new Random();

    public virtual double Get()
    {
        return Random.Next(100);
    }
}

public class Class1 : SomeClass { }

public class Class2 : SomeClass { }

public class Class3 : SomeClass { }

public abstract class CPD
{
    public double[,] Func<T>(double[] data, double value, T item)
    where T : SomeClass
    {
        var doubles = new double[3, 4];
        doubles[0, 0] = item.Get();
        return doubles;
    }

    public abstract double[] Fun1(double x);
    public abstract void Fun2(double x);
}
  • Related