在 C# 中将列表作为参数作为 ref 传递有什么好处?List 不是值类型,因此对它所做的每个更改都会在返回函数后反映出来。
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
var list = new List<string>();
myClass.Foo(ref list);
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
class MyClass
{
public void Foo(ref List<string> myList)
{
myList.Add("a");
myList.Add("b");
myList.Add("c");
}
}
Run Code Online (Sandbox Code Playgroud)
我可以删除“ref”,它会正常工作。所以我的问题是我们需要为列表、数组添加 ref 关键字有什么用途......谢谢
这将创建新列表并将替换list
来自外部的变量:
public void Foo(ref List<string> myList)
{
myList = new List<string>();
}
Run Code Online (Sandbox Code Playgroud)
这不会替换list
来自外部的变量:
public void Foo(List<string> myList)
{
myList = new List<string>();
}
Run Code Online (Sandbox Code Playgroud)
该REF关键字使一个参数通过引用传递,而不是值。列表是一种引用类型。在您的示例中,您还尝试使用 ref 关键字通过引用方法参数传递对象。
这意味着你在做同样的事情。在这种情况下,您可以删除ref关键字。
当您想通过引用传递某些值类型时,需要ref。例如:
class MyClass
{
public void Foo(ref int a)
{
a += a;
}
}
class Program
{
static void Main(string[] args)
{
int intvalue = 3;
var myClass = new MyClass();
myClass.Foo(ref intvalue);
Console.WriteLine(intvalue); // Output: 6
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到一些其他规范信息:ref(C# 参考)
归档时间: |
|
查看次数: |
7892 次 |
最近记录: |