为什么IEnumerable< T>仅具有“ out”状态协变量标志而不是“ in” C#? [英] Why does IEnumerable<T> only have the "out" covariant flag and not "in" c#?

查看:115
本文介绍了为什么IEnumerable< T>仅具有“ out”状态协变量标志而不是“ in” C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,为什么 IEnumerable< T> 仅具有 c而没有 in 逆向标志?

I was wondering , why does IEnumerable<T> has ONLY the out and not the in contravariant flag ?

public interface IEnumerable<out T>

通过此示例,我可以理解 out

I can understand the out by this example :

IEnumerable<string> strings = new List<string>(){"a","b","c"};
IEnumerable<object> objects = strings;

对象大于 string ,因此编译器担心做得好:

object is bigger than string , so the compiler afraid that well do something like:

 objects = objects.First().Select(x=>5);// ( we cant insert int to string...)

很好并且理解。

但是如果我想将IEnumerable用作插入怎么办?

but what about if i want to use the IEnumerable as insertion?

类似的东西:

IEnumerable<object> objects = ...;
IEnumerable<string> strings = objects

所以我也可以插入对象...

so i can also INSERT into objects ...

,但问题是T中没有 IEnumerable< ...

but the problem is that there is no IEnumerable<in T> ...

我在这里错过了什么吗?

am I missing something here?

推荐答案

您无法插入 IEnumerable 。不幸的是,没有 IInsertable。

You can't insert into IEnumerable. There is, unfortunately, no "IInsertable".

没有接口告诉您只能将项目添加到集合中。这将是 in 通用类型。因为您可以在每个集合界面上获取项目,所以不可能在通用参数中有

There is no interface to tell that you can only add items to a collection. This would be an in generic type. Because you can get the items on every collection interface, it is not possible to have in generic arguments.

编辑

接口 IEnumerable< T> 只有吸气剂,因此您不能使用该接口将任何元素插入到集合中。因此,在 IEnumerable< out T> 的声明中允许 out 。它告诉编译器,类型 T 的值仅朝一个方向运行,即出来。这使其在一个方向上兼容。您可以将 IEnumerable< string> 用作 IEnumerable< object> ,因为您只是从中读取。您可以将字符串作为对象读取。但是您无法写入,也无法将对象作为字符串传递。它可以是整数或任何其他类型。

The interface IEnumerable<T> has only getters, so you can't insert any elements to the collection using that interface. Because of that, out is allowed in the declaration of IEnumerable<out T>. It tells the compiler, that values of type T are only going in one direction, the are "coming out". This makes it compatible in one direction. You can use IEnumerable<string>as an IEnumerable<object>, because you are only reading from it. You can read a string as an object. But you couldn't write to it, you couldn't pass an object as a string. It might be an integer or any other type.

这篇关于为什么IEnumerable&lt; T&gt;仅具有“ out”状态协变量标志而不是“ in” C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆