관찰 정책 수집 에 어떻게 캐스팅 할 수 있습니까?
-
20-09-2019 - |
문제
어떻게 캐스팅 할 수 있습니까?
from ObservableCollection<TabItem> into ObservableCollection<object>
이것은 나에게 효과가 없습니다
(ObservableCollection<object>)myTabItemObservableCollection
해결책
이렇게 복사해야합니다
return new ObservableCollection<object>(myTabItemObservableCollection);
다른 팁
기본적으로, 당신은 할 수 없습니다. 지금은 아닙니다 .NET 4.0이 아닙니다.
여기서 컨텍스트는 무엇입니까? 뭐가 필요하세요? LINQ가 있습니다 Cast<T>
데이터를 a로 얻을 수 있습니다 순서, 또는 일반적인 방법을 가진 몇 가지 트릭이 있습니다 (즉 Foo<T>(ObservalbleCollection<T> col)
등).
또는 비 게 니체 만 사용할 수 있습니다 IList
?
IList untyped = myTypedCollection;
untyped.Add(someRandomObject); // hope it works...
당신은 사용할 수 있습니다 IEnumerable.Cast<T>()
당신은 할 수 없습니다. ObservableCollection<TabItem>
파생되지 않습니다 ObservableCollection<object>
.
왜 당신이 원하는지 설명하면 아마도 우리는 당신이 사용할 수있는 대체 인터페이스를 지적 할 수 있습니다.
모든 답변에 대한 고맙습니다. 그러나 나는이 문제를 "헬퍼 메드"로 해결했다고 생각합니다.
아마도 더 나은 방법이나 LINQ 문이있을 것입니다.
private void ConvertTabItemObservableCollection()
{
Manager manager = this.container.Resolve<Manager>();
foreach (var tabItem in manager.ObjectCollection)
{
TabItemObservableCollection.Add((TabItem)tabItem);
}
}
내가 찾은 예 중 어느 것도 나를 위해 일하지 않았으며, 아래 코드를 함께 모았으며 효과가있는 것 같습니다. 나는 XML 파일을 사로화하여 생성되는 계층 구조를 가지고 있으며 계층 구조의 모든 객체를 루프 할 수 있지만 하나의 관측형 정책 수집을 통해 반복하고 객체를 객체로 가져 와서 강하게 입력하지 않은 객체를 얻을 수 있습니다.
UNDO/REDO 기능을 구현할 수 있도록 계층 구조의 모든 속성에 PropertyChangingEventhandler를 추가하고 싶습니다.
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
}
}
}
}
}
}
이 방법은 방금 이렇게 불립니다
TraversalHelper.TraverseAndExecute(object);
객체 모음을 만들고 싶다면이 코드가 필요합니다.
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
}
inotifyCollectionChanged로 캐스팅 할 수 있습니다.
처럼:
if (myTabItemObservableCollection is INotifyCollectionChanged collection)
{
Do Stuff
}