使用“ref”键将“引用类型”作为参数传递给方法是否有意义?
可能重复:
C#:参考类型变量的“ref”有什么用?
嗨,
使用“ref”键将“引用类型”作为参数传递给方法是否有意义?
或者它只是废话,因为它已经是引用类型但不是值类型?
谢谢!
它允许您更改引用变量本身 ,以及它指向的对象。
如果您认为可能使变量指向方法内的不同对象(或为null
),则这是有意义的。
否则,没有。
将引用类型作为ref传递时,您将引用作为引用传递,这可能有意义。 这意味着该方法可以替换引用,如果它希望:
public void CallRef() { string value = "Hello, world"; DoSomethingWithRef(ref value); // Value is now "changed". } public void DoSomethingWithRef(ref string value) { value = "changed"; }
如果有所作为,因为它允许方法更改变量指向的实例。
换句话说,当您想要使变量指向引用类型的不同实例时,可以使用它。
private static void WithoutRef(string s) { s = "abc"; } private static void WithRef(ref string s) { s = "abc"; } private static void Main() { string s = "123"; WithoutRef(s); Console.WriteLine(s); // s remains "123" WithRef(ref s); Console.WriteLine(s); // s is now "abc" }
ref in C#允许您修改实际变量。
看看这个问题 – C#中引用类型变量的“ref”有什么用? – 包括这个例子
Foo foo = new Foo("1"); void Bar(ref Foo y) { y = new Foo("2"); } Bar(ref foo); // foo.Name == "2"
这不是废话。 当您这样做时,您将通过引用传递引用。
例:
class X { string y; void AssignString(ref string s) { s = "something"; } void Z() { AssignString(ref this.y}; } }
如果您希望传入的传入变量更改其指针,则会执行此操作。
请考虑以下代码。 你期望的是这个程序的输出?
string s = "hello world"; Console.WriteLine(s); foo(s); Console.WriteLine(s); bar(ref s); Console.WriteLine(s); void foo(string x) { x = "foo"; } void bar(ref string x) { x = "bar"; }
输出是:
hello world hello world bar
在调用方法bar
,您将通过引用(而不是值)传递对字符串s
的引用,这意味着s
将在调用站点处更改。