通过列表<T>通过参考接受 ref ICollection 的方法; [英] Passing List<T> by reference to a method accepting ref ICollection<T>

查看:62
本文介绍了通过列表<T>通过参考接受 ref ICollection 的方法;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 List 不能传递给方法,例如:

I've noticed that a List<T> cannot be passed to methods such as:

  • Foo(ref ICollection bar)
  • Foo(out ICollection bar)

考虑到另一方面,Foo(ICollection bar) 确实接受 List 作为参数,任何人都可以请向我解释所描述的行为?

Taking into account that, on the other side, Foo<T>(ICollection<T> bar) does accept a List<T> as argument, could anyone please explain the described behavior to me?

完整示例:

public class AuxClass { }

public class Test
{
    private void NonRefFoo<T>(ICollection<T> intCollection) {; }
    private void RefFoo<T>(ref ICollection<T> intCollection) {; }
    private void OutFoo<T>(out ICollection<T> intCollection) { intCollection = null; }

    public void Foo()
    {
        {
            List<int> list = new List<int>() { 0, 1, 2, 3, 5, 8, 13 };
            List<AuxClass> classList = new List<AuxClass>() { new AuxClass() };

            NonRefFoo<int>(list);
            RefFoo<int>(ref list);                                  // Invalid
            OutFoo<AuxClass>(out List<int> outListInt);             // Invalid

            NonRefFoo<AuxClass>(classList);
            RefFoo<AuxClass>(ref classList);                        // Invalid
            OutFoo<AuxClass>(out List<AuxClass> outListClass);      // Invalid
        }

        {
            ICollection<int> collection = new List<int>() { 0, 1, 2, 3, 5, 8, 13 };
            ICollection<AuxClass> classCollection = new List<AuxClass>() { new AuxClass() };

            NonRefFoo<int>(collection);
            OutFoo<int>(out ICollection<int> outCollectionInt);
            RefFoo<int>(ref collection);

            NonRefFoo<AuxClass>(classCollection);
            RefFoo<AuxClass>(ref classCollection);
            OutFoo<AuxClass>(out ICollection<AuxClass> outCollectionClass);
        }
    }
}

提前致谢

推荐答案

使用 ref 有一种可能性(并且确定性)您将为传入的属性分配一个新对象.在这种情况下,任何输入 ICollection.如果传入 List 类型的对象,您最终可能会分配一个实现 ICollection 的无关类型的对象.c# 类型系统不允许这样做,编译器知道这一点,因此阻止您这样做

With the ref there is a possibility (and with the out a certainty) that you will assign a new object to property you pass in. In this case anything of type ICollection<T>. If you pass in an object of type List<T> you might end up assigning an object of a unrelated type that implements ICollection<T>. The c# type system doesn't allow that and the compiler knows this and so stops you doing it

这篇关于通过列表&lt;T&gt;通过参考接受 ref ICollection 的方法;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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