我不清楚为什么以下代码片段不是协变的?
public interface IResourceColl<out T> : IEnumerable<T> where T : IResource {
int Count { get; }
T this[int index] { get; }
bool TryGetValue( string SUID, out T obj ); // Error here?
}
错误1:无效的方差:类型参数'T'必须在'IResourceColl.TryGetValue(string, out T)'上不变地有效。'T'是协变的。
我的接口只在输出位置使用模板参数。我可以轻松地将此代码重构为以下内容:
public interface IResourceColl<out T> : IEnumerable<T> where T : class, IResource {
int Count { get; }
T this[int index] { get; }
T TryGetValue( string SUID ); // return null if not found
}
但是我正在努力理解我的原始代码是否实际上违反了协变,或者这是协变的编译器或.NET限制。
out
(参数修饰符)与out
(用于泛型类型参数)完全不相关。 - Jon