【发布时间】:2018-01-05 07:43:40
【问题描述】:
我正在阅读一个让我停在某行的代码:
List<object> props = new List<object>();
DoWork(param1, param2, props);
//props.Count grew up
我在想,更改其范围之外的变量需要将其作为out 或ref 传递,但后来我意识到除非DoWork 方法更改props 引用,如:
props = new List<object>();
引用将指向相同的位置。所以这里不需要使用ref。
然后我为string 类型创建了一个方法:
static void ChangeMe(string str)
{
str = "W77";
}
public static void Main(string[] args)
{
string str = "p1";
ChangeMe(str);
//str is still "p1"
}
如果促使 List 在其范围之外进行更改的行为是它的引用类型,为什么 string 没有在被调用方方法中重新分配并且它是像 List<object> 这样的引用类型时不会改变?
【问题讨论】:
标签: c# ref out reference-type