0

I'm coding a game with cocosharp in C# for iOS. I want to have an object that will store different objects from different classes and through this object I want call public methods from this objects. The problem is that active object can be from three different classes with public methods with same name. My vision is like this:

//object for store active object
General_class active_object = new General_class();

//my_game_object is active layer now
active_object = my_game_object;


// pop_in() is method that has same name in different classes
active_object.pop_in();

My question is if is something like this even possible and what should be the General_class class.

Thank you

edit

I forgot to mention that my_game_object inherits from CCLayer class from cocossharp library.

edit 2

This thread solves my problem.

Community
  • 1
  • 1
  • Create an abstract base class for your layer, then have three different concrete classes that inherit from the base class. – Jason Sep 18 '15 at 13:01

3 Answers3

4

Easy, make those three classes implement an interface:

public interface ILayer
{
    void pop_in();
}

// one of your classes
public class SomeLayer : ILayer
{
    // ...
}

//object for store active layer
ILayer active_layer = new SomeLayer();

// rest of the code works

Although I suspect that probably means your basic knowledge of C# is limited. Perhaps you should grab a book.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • Thank you. Yep I'm starting with C#. I forgot to mention that my_game_object inherits from CCLayer class from cocosharp library. – Jozef Mrkva Sep 18 '15 at 13:13
0

Define an interface, and add it as the interface on each of your three classes:

public interface ILayer
{
    void pop_in();
}

public GameLayer : ILayer
{
    public void pop_in()
    {
        // GameLayer-specific implementation
    }
}

Then your code becomes:

//object for store active layer
ILayer active_layer = // Whatever your default active layer is

//my_game_layer is active layer now
active_layer = my_game_layer;

// pop_in() is method that has same name in different classes
active_layer.pop_in();
Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
0

Make a top level interface that declares the method which is common to all the classes in question here. Then create all the classes you require by implementing the interface and define the method with the same signature as in the interface in each of these concrete classes. And don't worry about the correct method being called at runtime, polymorphism would do its job perfectly.

zulkarnain shah
  • 971
  • 9
  • 20