传递IEnumerable是否重要?
作者:互联网
只需仔细检查一下我对引用/值语义的理解即可:
假设我做了一个List< T>值=新的List< T>();
>如果T是引用类型,则值包含对T集合的引用.但是,此集合的每个元素都是对数据的引用.
>如果T是值类型,则值包含对T集合的引用.但是,此集合的每个元素都包含实际数据.
引起我的好奇心是因为我试图设计一种需要IEnumerable T的方法.因此,如果我给它一个List< int>或List< SomeObject> ;,它的工作方式完全相同,T的类型无关紧要,每个人都很高兴,因为它是对所提供集合的引用,是吗?
public sealed class Effect<T>
{
public void Apply(GameTime time, IEnumerable<T> values)
{
...
}
}
也!与拳击无关,对吗?由于List< T>具有参考语义,仅IEnumerable< T>的结构实现.将涉及拳击(但这似乎是一场灾难,等待发生)
解决方法:
您的理解是正确的.
My curiosity arose because I was trying to design a method which required an
IEnumerable<T>
. So if I give it aList<int>
or aList<SomeObject>
, it works exactly the same way, the type of T is irrelevant and everyone is happy, since it’s a reference to the collection that is being provided, yes?
是的,值是对集合的引用.这不会影响其项目的性质.
Also! This has nothing to do with boxing, right? Since
List<T>
has reference semantics, only a struct implementation ofIEnumerable<T>
would involve boxing (but this seems like a disaster waiting to happen)
是;通用集合的全部目的是避免完全装箱.列表本身及其值类型项都不装箱(除非列表本身是List< object> ;,在这种情况下,将其项装箱).
标签:collections,generics,parameter-passing,c,net 来源: https://codeday.me/bug/20191029/1959826.html