您的位置:首页 > 其它

Why IEnumerable<T> is defined as IEnumerable<out T>, not IEnumerable<T>

2013-05-17 10:40 267 查看
http://stackoverflow.com/questions/12424537/why-ienumerablet-is-defined-as-ienumerableout-t-not-ienumerablet

The
out
type parameter specifier denotes covariance.

In practice,

If I define two interfaces.

[code]ISomeInterface<T>{}

ISomeCovariantInterface<out T>{}
[/code]
Then, I implement them like this.

[code]SomeClass<T>:ISomeInterface<T>,ISomeCovariantInterface<T>{}
[/code]
Then I try to compile this code,

[code]ISomeCovariantInterface<object>=newSomeClass<string>();// works

ISomeInterface<object>=newSomeClass<string>();// fails
[/code]
The is because the covariant interface allows more derived instances, where as, the standard interface does not.

public interface ISomeInterface<T> { }

public interface ISomeCovariantInterface<out T> { }

public class SomeClass<T> : ISomeInterface<T>, ISomeCovariantInterface<T> { }

var obj = new SomeClass<string>();

ISomeCovariantInterface<object> obj1 = obj;// works
ISomeCovariantInterface<string> obj2 = obj;// works
ISomeInterface<string> obj3 = obj;//work
//ISomeInterface<object> obj4 = obj;//不可编译
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐