只需仔细检查我对引用/值语义的理解:
假设我做了一个 List<T> values = new List<T>();
如果T 是引用 类型,则
values
包含对 T 集合的引用。但是,此集合的每个元素都是对数据的引用。如果T 是值 类型,则
values
包含对 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?
是的,values
是对集合的引用。这不会影响其项目的性质。
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>
,在这种情况下,其项目已装箱)。
关于c# - 传递 IEnumerable<T> 时 T 重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24364676/