2

ジェネリックの使用に問題があります。次のように定義された汎用キー値ペアの汎用コレクションがあります。

public class KeyValueTemplate<K, V> : IGetIdentifier<K>
{
//...
}

public class KeyValueListTemplate<K, V> : ObservableCollection<KeyValueTemplate<K, V>>
{
//....
}

public class KeyValueStringListTemplate : KeyValueListTemplate<string,string> { }

次のようにコードでこれを使用しています

public class test
{

   public KeyValueStringListTemplate SetValuesList{get;set;}
   public ObservableCollection<IGetIdentifier<string>> GetList()
   {
     return SetValuesList;
   }

}

コンパイラはこれを受け入れていません。エラーは

Cannot convert type 'KeyValueStringListTemplate' to 'System.Collections.ObjectModel.ObservableCollection<IGetIdentifier<string>>

どうして??どちらのタイプも私には同じです。

4

2 に答える 2

2

この行

public class KeyValueListTemplate<K, V> : ObservableCollection<KeyValueTemplate<K, V>>

KeyValueListTemplateは、 のサブタイプである新しい型 を定義しているObservableCollectionため、これらは異なる型です。は の機能のスーパーセットを持っているため(リスコフ置換原理による) にKeyValueListTemplate安全に変換できますが、逆の変換は安全ではありません。ObservableCollectionObservableCollection

于 2012-06-29T12:01:37.223 に答える
1

これは、.net 4 より前に c#/vb.net に公開されていなかったジェネリックの共分散の問題です

IEnumerable<string> strings = new List<string>();
// An object that is instantiated with a more derived type argument 
// is assigned to an object instantiated with a less derived type argument. 
// Assignment compatibility is preserved. 
IEnumerable<object> objects = strings;

これはあなたのコードが一番下の行で行っていることであり、.net 4 まではサポートされ
ていませんでした。

于 2012-06-29T12:13:30.207 に答える