c# - 传递 IEnumerable<T> 时 T 重要吗?

标签 c# .net generics collections parameter-passing

只需仔细检查我对引用/值语义的理解:

假设我做了一个 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 a List<int> or a List<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 of IEnumerable<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/

相关文章:

c# - Windows Phone 8.1 应用程序中的 routeResult.Status 不断给出无效凭据错误消息

asp.net - .Net 应用程序仅在用户访问根 URL 时重定向用户进行身份验证

java - 在 Java 中,我可以指定任意数量的泛型类型参数吗?

c# - WrapGrid 和大量图像

c# - 用于跨平台 Xamarin Forms 的用户控件

c# - C#中多个参数占用多行

c# - 为什么 File.OpenRead() 将相对路径附加到可执行文件?

使用数值泛型进行 Scala 运算

c# - 如果在运行时只知道类型参数,如何调用泛型方法?

C# RSACryptoServiceProvider ToXmlString()/FromXmlString() 方法