LukeP
LukeP

Reputation: 1605

Get list of interface

I am new to interfaces but I'm trying to force myself learn how to use them. I am confused on how to go about selecting a list of objects that implement an interface. This is the gist what I have so far:

public class Planet 
{
    public ICollection<Structure> Structures {get;set;}
    public ICollection<Ship> Ships {get;set;}
    public int GatherRate {get;set}
    public void GetAllResourceGatherers
    {
        var resourceGatherers = Planet.Ships.OfType<IResourceGatherer>()
                                                .ToList();

        //the below line doesn't work. I want to be able to get a list of all 
        //ships and structures that implement IResourceGatherer.    
        resourceStorers.AddRange(Structures.OfType<IResourceGatherer>()
                                               .ToList());

        foreach (var gatherer in resourceGatherers)
        {
            GatherRate += gatherer.GatherRate;
        }
    }
}
public class Ship
{
    //Stuff that all ships should have such as health, speed, cost, etc
}
public class Structure
{
    //Stuff that all structures should have such as buildtime, cost, etc
}
public class ResourceStructure : Structure, IResourceGatherer
{
    //implement interface
}
public class ResourceShip : Ship, IResourceGatherer
{
    //implement interface
}
interface IResourceGatherer
{
    int GatherRate{get;set;}
}

Is there a better way to do this?

P.S. I'm using Entity Framework 6 and MVC 4 on this project.

Upvotes: 1

Views: 138

Answers (2)

Aaron Palmer
Aaron Palmer

Reputation: 9002

Perhaps something along these lines:

var resourceGatherers = new List<IResourceGatherer>();

var gathererShips = Planet.Ships.OfType<IResourceGatherer>().ToList();

var gathererStructures = Structures.OfType<IResourceGatherer>().ToList();

resourceGatherers.AddRange(gathererShips);
resourceGatherers.AddRange(gathererStructures);

Upvotes: 1

AgentFire
AgentFire

Reputation: 9790

Well, you are trying to get IResourceGather interface implementators from Ships property of a Planet. Note that property is of type ICollection<Ship>. Now tell me, does Ship implement IResourceStorer?

I bet it doesn't. That's why you get empty select result.

According to the update:

Well, you are trying to get IResourceGather interface implementators from Structures property of a Planet. Note that property is of type ICollection<Structure>. Now tell me, does Structure implement IResourceStorer?

I bet it doesn't. That's why you get empty select result.


The only option when you can have non-empty result is when you add some extended ships into the list:

Structures.Add(new ResourceStructure());

Upvotes: 2

Related Questions