¿Cómo puedo enviar contenido¿Cómo puedo echar en un ObservableCollection <object>
from ObservableCollection<TabItem> into ObservableCollection<object>
esto no funciona para mí
(ObservableCollection<object>)myTabItemObservableCollection
¿Cómo puedo enviar contenido¿Cómo puedo echar en un ObservableCollection <object>
from ObservableCollection<TabItem> into ObservableCollection<object>
esto no funciona para mí
(ObservableCollection<object>)myTabItemObservableCollection
debería copiar como esto
return new ObservableCollection<object>(myTabItemObservableCollection);
has olvidado la palabra clave 'new' –
gracias Dr ew, lo agregué –
.net 4 NO resuelve este problema como se detalla en la publicación de Marc Gravell. – MrSlippers
No se puede. ObservableCollection<TabItem>
no deriva de ObservableCollection<object>
.
Si explica por qué lo desea, quizás podamos señalar una interfaz alternativa que puede utilizar.
Básicamente, no se puede. Ahora no, y not in .NET 4.0.
¿Cuál es el contexto aquí? ¿Que necesitas? LINQ tiene Cast<T>
que puede obtener los datos como una secuencia , o hay algunos trucos con métodos genéricos (es decir, Foo<T>(ObservalbleCollection<T> col)
, etc.).
O simplemente puede utilizar el IList
no genérico?
IList untyped = myTypedCollection;
untyped.Add(someRandomObject); // hope it works...
podría utilizar IEnumerable.Cast<T>()
gracias por todas las respuestas, pero creo que tengo resolver este mismo problema con un "helpermethode".
Quizás tenga algún método mejor o una declaración de linq para esto.
private void ConvertTabItemObservableCollection()
{
Manager manager = this.container.Resolve<Manager>();
foreach (var tabItem in manager.ObjectCollection)
{
TabItemObservableCollection.Add((TabItem)tabItem);
}
}
Como no sabemos cómo se escribe ObjectCollection, es bastante difícil de responder ... –
¡No entiendo lo que quiere decir ?! Tengo un TabItem lo que me gustaría agregar a un ObservableCollection de tipo object. "Manager" es una clase global con un ObservableCollection
Ah, lo siento, he entendido mal su respuesta. "ObjectCollection" se escribe como objeto ObservableCollection
Ninguno de los ejemplos que he encontrado me funcionaron, he ensamblado el siguiente código y parece que funciona. Tengo una jerarquía que se crea deserializando un archivo XML y puedo recorrer todos los objetos de la jerarquía, pero puedes adaptar esto para simplemente hacer un ciclo a través de una ObservableCollection y obtener los objetos como objetos y no fuertemente tipados.
Quiero agregar un PropertyChangingEventHandler a cada propiedad en la jerarquía para que pueda implementar la funcionalidad de deshacer/rehacer.
public static class TraversalHelper
{
public static void TraverseAndExecute(object node)
{
TraverseAndExecute(node, 0);
}
public static void TraverseAndExecute(object node, int level)
{
foreach (var property in node.GetType().GetProperties())
{
var propertyValue = node.GetType().GetProperty(property.Name).GetGetMethod().Invoke(node, null); // Get the value of the property
if (null != propertyValue)
{
Console.WriteLine("Level=" + level + " : " + property.Name + " :: " + propertyValue.GetType().Name); // For debugging
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(ObservableCollection<>)) // Check if we are dealing with an observable collection
{
//var dummyvar = propertyValue.GetType().GetMethods(); // This was just used to see which methods I could find on the Collection
Int32 propertyValueCount = (Int32)propertyValue.GetType().GetMethod("get_Count").Invoke(propertyValue, null); // How many objects in the collection
level++;
for (int i = 0; i < propertyValueCount; i++) // Loop over all objects in the Collection
{
object properyValueObject = (object)propertyValue.GetType().GetMethod("get_Item").Invoke(propertyValue, new object[] { i }); // Get the specified object out of the Collection
TraverseAndExecute(properyValueObject, level); // Recursive call in case this object is a Collection too
}
}
}
}
}
}
El método se acaba de llamar como esto
TraversalHelper.TraverseAndExecute(object);
Si lo que desea es crear una colección de objetos que sólo tiene este fragmento de código
ObservableCollection<Field> typedField = migration.FileDescriptions[0].Inbound[0].Tables[0].Table[0].Fields[0].Field; // This is the strongly typed decalaration, a collection of Field objects
object myObject = typedField; // Declare as object
Int32 propertyValueCount = (Int32)myObject.GetType().GetMethod("get_Count").Invoke(myObject, null); // How many objects in this Collection
for (int i = 0; i < propertyValueCount; i++) // Loop over all objects in the Collection
{
object properyValueObject = (object)myObject.GetType().GetMethod("get_Item").Invoke(myObject, new object[] { i }); // Get the specified object out of the Collection, in this case a Field object
// Add the object to a collection of objects, or whatever you want to do with object
}
que se llama la covarianza, y todavía no está disponible en C# –
(y para colecciones, no estará disponible en 4.0 tampoco - para ser claro) –