不幸的是,KeyValuePair<TKey, TValue>
是一个结构体;而结构体在.NET中没有表现出变化。
当然,您可以通过编写自己的协变 Pair
接口并编写一些简单的帮助程序来转换 KeyValuePair
序列和您的自定义 Pair
接口之间的序列来解决此问题。 这将使您能够执行以下操作:
var dict = new Dictionary<string, ICollection<string>>();
var view = dict.GetCovariantView();
var dictView = view.CastPairs<object, IEnumerable<string>>();
IEnumerable< IPair< Object, IEnumerable<String> > > dictView2 = view;
Console.WriteLine( Object.ReferenceEquals( view, dictView2 ) );
以下是一些示例代码,可以帮助您实现此功能:
public interface IPair<out TKey, out TValue>
where TKey : notnull
{
TKey Key { get; }
TValue Value { get; }
}
public class Pair<TKey, TValue> : IPair<TKey, TValue>
where TKey : notnull
{
public TKey Key { get; }
public TValue Value { get; }
public Pair(TKey key, TValue value)
{
this.Key = key;
this.Value = value;
}
public Pair(KeyValuePair<TKey, TValue> pair)
: this(pair.Key, pair.Value)
{}
}
public static class PairSequenceExtensions
{
public static IEnumerable<IPair<TKey, TValue>> GetCovariantView<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source)
where TKey : notnull
{
if (source is null) throw new ArgumentNullException(nameof(source));
return source.Select(kvp => new Pair<TKey, TValue>(kvp));
}
public static IEnumerable<IPair<TKey, TValue>> CastPairs<TKey, TValue>(this IEnumerable<IPair<TKey, TValue>> source)
where TKey : notnull
{
if (source is null) throw new ArgumentNullException(nameof(source));
return source;
}
}