是ILists按值传递? [英] Are ILists passed by value?

查看:123
本文介绍了是ILists按值传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类型参数在C#中的功能是值,除非您使用的ref或列于参数关键字。但是,这是否也适用于引用类型的?



具体来说,我有一个函数,它接受一个的IList<富> 。将传递给我的函数列表是列表的副本,其包含的对象的副本?或将修改列表也适用于来电?如果是这样的 - 是否有一个聪明的方法我可以去传递一个副本?

 公共无效SomeFunction()
{
&IList的LT;富>名单=新名单,LT;富>();
list.Add(新的Foo());
DoSomethingWithCopyOfTheList(名单);
..
}

公共无效DoSomethingWithCopyOfTheList(IList的<富>清单)
{
//做些什么
}


解决方案

所有的参数是按值传递,除非你明确地用 REF 退出。然而,当你传递引用类型的实例,您通过值的参考。即引用本身被复制,但是由于它仍然指向同一个实例,你仍然可以通过这个参考修改实例。即实例是不可复制的。该参考。



如果你想使名单本身的副本,列表< T> 拥有的handy构造,这需要一个的IEnumerable< T>


Passing Value Type parameters to functions in c# is by value unless you use the ref or out keyword on the parameter. But does this also apply to Reference Types?

Specifically I have a function that takes an IList<Foo>. Will the list passed to my function be a copy of the list with copy of its contained objects? Or will modifications to the list also apply for the caller? If so - Is there a clever way I can go about passing a copy?

public void SomeFunction()
{
    IList<Foo> list = new List<Foo>();
    list.Add(new Foo()); 
    DoSomethingWithCopyOfTheList(list);
    ..
}

public void DoSomethingWithCopyOfTheList(IList<Foo> list)
{
    // Do something
}

解决方案

All parameters are passed by value unless you explicitly use ref or out. However, when you pass an instance of a reference type, you pass the reference by value. I.e. the reference itself is copied, but since it is still pointing to the same instance, you can still modify the instance through this reference. I.e. the instance is not copied. The reference is.

If you want to make a copy of the list itself, List<T> has a handy constructor, that takes an IEnumerable<T>.

这篇关于是ILists按值传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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