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

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

问题描述

值类型参数传递给 c# 中的函数是按值传递的,除非您在参数上使用 ref 或 out 关键字.但这是否也适用于引用类型?

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?

具体来说,我有一个接受 IList 的函数.传递给我的函数的列表是否是列表的副本及其包含的对象的副本?或者对列表的修改也适用于调用者?如果是这样 - 有没有一种聪明的方法可以传递副本?

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
}

推荐答案

所有参数都按值传递,除非您明确使用 refout.但是,当您传递引用类型的实例时,您是按值传递引用.IE.引用本身被复制,但由于它仍然指向同一个实例,你仍然可以通过这个引用修改实例.IE.不复制实例.参考是.

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.

如果您想制作列表本身的副本,List 有一个 方便的构造函数,它接受一个 IEnumerable.

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

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

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