IList 是按值传递的吗?
将 值类型 参数传递给 C# 中的函数是按值传递,除非您使用参数上的 ref 或 out 关键字。但这是否也适用于引用类型?
具体来说,我有一个接受 IList
的函数。传递给我的函数的列表是否是列表的副本及其所包含对象的副本?或者对列表的修改也适用于调用者吗?如果是这样 - 有什么聪明的方法可以让我传递一份副本吗?
public void SomeFunction()
{
IList<Foo> list = new List<Foo>();
list.Add(new Foo());
DoSomethingWithCopyOfTheList(list);
..
}
public void DoSomethingWithCopyOfTheList(IList<Foo> list)
{
// Do something
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(6)
你并不孤单;这让很多人感到困惑。
我喜欢这样想。
变量是一个存储位置。
变量可以存储特定类型的内容。
有两种类型:值类型和引用类型。
引用类型变量的值是对该类型对象的引用。
值类型变量的值是该类型的对象。
形式参数是一种变量。
形式参数分为三种:值参数、引用参数和输出参数。
当您使用变量作为与值形参相对应的实参时,变量的值将被复制到与形参关联的存储中。如果变量是值类型,则创建该值的副本。如果变量是引用类型,则创建引用的副本,并且两个变量现在引用同一个对象。无论哪种方式,都会生成变量值的副本。
当您使用变量作为对应于 out 或 ref 参数的实参时,该参数将成为该变量的别名。当您说:
void M(ref int x) { ...}
...
int y = 123;
M(ref y);
您所说的是“x 和 y 现在是同一个变量”。它们都指相同的存储位置。
我发现这比思考别名是如何实际实现的——通过将变量的托管地址传递给形式参数——更容易理解。
清楚了吗?
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
所有参数均按值传递,除非您显式使用
ref
或out
。但是,当您传递引用类型的实例时,您是按值传递引用。即引用本身被复制,但由于它仍然指向同一个实例,因此您仍然可以通过此引用修改实例。即实例未被复制。参考是。如果您想复制列表本身,
List
有一个 方便的构造函数,它采用IEnumerable
。All parameters are passed by value unless you explicitly use
ref
orout
. 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 anIEnumerable<T>
.