저는 종종이 문제에 직면했습니다. 키가 단순한 숫자 ID이고 값이 객체 인 사전이 있습니다. ID는 해당 값 객체의 특정 속성에도 포함됩니다.사전 <K,V>은 IList를 구현합니다. <V>
는 다음, 나는처럼 보이는 일부 (포맷 유연성) XML 직렬화 할 수 있도록하려면 :
<listitem>
<id>20359</id>
<someotherval>foo</someotherval>
</listitem>
<listitem>
...
이것은 List<V>
와 역 직렬화 나에게 요구를하고, 수동에 그것을 변환해야하는 불편 a Dictionary<K,V>
.
두 번째 문제는 바인딩 때문입니다. 바인딩 목록을 사용하려면 소스가 ICollection
(올바르게 기억하는 경우)을 구현해야하며 다시 List<V>
을 수동으로 만들어 Dictionary<K,V>
에서 채워야합니다.
public abstract class Keyed<KeyType>
{
public KeyType key { get; set; }
}
public class KeyedDictionary<KeyType, ValueType> :
Dictionary<KeyType, ValueType>
where ValueType : Keyed<KeyType>
{
// ...
}
public class KeyedList<KeyType, ValueType> :
IList<ValueType>,
System.Collections.IList
where ValueType : Keyed<KeyType>
{
public readonly KeyedDictionary<KeyType, ValueType> dict =
new KeyedDictionary<KeyType, ValueType>();
// ...
}
이 작동하지만, 내부적으로 크고 추한 :
나의 현재, 매우 추악한하지만 기능적인 솔루션은 다음과 같은 수업을하는 것입니다. 더 좋은 방법이 있습니까?
편집 : 여기에 해결 방법이 있습니다.
public interface IKeyed<KeyType>
{
KeyType Key { get; }
}
public class KeyedList<KeyType, ValueType> :
KeyedCollection<KeyType, ValueType>
where ValueType : IKeyed<KeyType>
{
protected override KeyType GetKeyForItem(ValueType item) { return item.Key; }
}
사실 저에게는 꽤 좋은 것처럼 보입니다. 요구 사항을 충족하며 단순한 제네릭 및 인터페이스를 제공합니다. –
질문이 C# 프로그래밍 언어에 관한 것이 아니라면 "C#"을 제목에서 제외하십시오. 이 질문은 C#에 관한 것이 아니라 .NET에 관한 것입니다. C#은 .NET을 사용할 수 있도록 작성한 언어입니다. –