Extensiones genéricas

I want to create a set of extensions similiar to the .ToList<>() for a custom Generic Colletion I have.

Here are the Objects I have

AceDataObjectCollection<T> : ICollection<T> where T : IAceDataObject
IAceDataBlock : IAceDataObject
IAceMessage : IAceDataObject

Quiero hacer esto.

AceDataObjectCollection<IAceDataObject> objects = new AceDataObjectCollection<IAceDataObject>();
objects.Add(...)  // Add different data objects here
AceDataObjectCollection<IAceMessage> messages = objects.Where(o => o is IAceMessage).ToAceDataObjectCollection<IAceMessage>();

I can't seem to figure out how to form the extension properly with the generics.

preguntado el 08 de noviembre de 11 a las 16:11

Slightly off topic, but you may be interested in the OfType LINQ method. So instead of your Where call, you could just say .OfType<IAceMessage>() -

1 Respuestas

Creo que esto es lo que estás buscando.

public static AceDataObjectCollection<T> ToAceDataObjectCollection<T>(this IEnumerable<T> col) where T : IAceDataObject 
   AceDataObjectCollection<T> objects = new AceDataObjectCollection<T>();

   foreach (T item in col)

   return objects; 

respondido 08 nov., 11:20

This is exactlly what I needed. I was missing the 'where T : IAceDataObject' Portion. Thanks very much. - Neal

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