简体   繁体   中英

C# - Polymorphism of classes inside array

I am trying to utlise polymorphism for class instances inside an Object array:

ClassA a = new ClassA();
ClassB b = new ClassB();

Object[] classes = new Object[] { a, b };

An example of one of the classes would be:

public class ClassA 
{
    public string PrintOutput()
    {
        return "254,62,455,5,15,62,656";
    }
}

I've tried something similar to: C# class polymorphism

The issue this person had was that they created an array of type A (one of the classes). Changing the array type to Object leads to the error: object not containing a definition for the method/no accessible extension method accepting a first argument of type object could be found.

EDIT: At the moment, I'm just trying to print the outputs from the method in each class:

foreach (Object obj in classes)
{
    Console.WriteLine(obj.PrintOutput());
}

obj.PrintOutput() is where I get the above error.

One way is using common interface

public interface IPrintOutput
{
    string PrintOutput();
}

public class ClassA : IPrintOutput
{
    public string PrintOutput()
    {
         return "254,62,455,5,15,62,656";
    }
}

public class ClassB : IPrintOutput
{
    public string PrintOutput()
    {
         return "something else";
    }
}

IPrintOutput[] classes = new IPrintOutput[] { a, b };

Second way you can override ToString and use it (every object has ToString)

A common interface is the best solution. Another solution is define classes as dynamic:

 dynamic[] classes = new Object[] { a, b };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM