¿Cómo haría esta lista dinámica en C # 4.0?

This might not be possible without serializing the object to a byte array, but I want to have a collection of objects where the only common properties will be an int y una bool:

public class Speakers : IStereoComponents
{
     public int Id { get; set; }
     public bool RemoveMe { get; set; }
     public string SomethingElse { get; set; }
}

public class Receiver : IStereoComponents
{
    public int Id { get; set; }
    public bool RemoveMe { get; set; }
    public IList<string> Buttons { get; set; }
}

public interface IStereoComponents
{
     int Id { get; set; }
     bool RemoveMe { get; set; }
}

What I want to do is be able to add these items to a list or dictionary and either remove or add them based on Id and the RemoveMe field. I want to be able to do something like:

foreach (var component in components) component.RemoveMe == true;

Is there an easy way to do this? The only way I can think of doing it is using reflection, serializing everything into a byte[], except for the Id and RemoveMe properties. This will be a chore, I was hoping there's a fancy C# 4.0 of doing this? Or something completely obvious I'm missing?

preguntado el 27 de agosto de 11 a las 17:08

1 Respuestas

No need for reflection! Just make a List<IStereoComponents>:

var components = new List<IStereoComponents>();
components.Add(new Speakers { Id = 1, RemoveMe = false, SomethingElse = "100W" });
components.Add(new Receiver { Id = 2, RemoveMe = false, Buttons = new List<string>() });

Then, you can loop through them as you please:

foreach (var component in components)
{
    if (listOfIdsToRemove.Contains(component.Id))
        component.RemoveMe = true;
}

The beauty of interfaces is that you don't really care what else the object can do: as long as it does what the interface requires, that's enough.

Respondido 27 ago 11, 21:08

Also take the public modifier off RemoveMe in the interface and change == to = in the foreach. - TrueWill

And just FYI if the List class doesn't support your needs the System.Collections.Generic namespace has a whole bunch of typed collections that might provide the extra methods you need. - Phil

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.