两个方法与ref对象par和没有?有什么区别?
我想知道以下方法在引用对象参数方面的区别是什么:
public void DoSomething(object parameter){}
和
public void DoSomething(ref object parameter){}
如果我想更改object
的引用而不是覆盖同一引用中的对象,我应该使用ref object parameter
吗?
public void DoSomething(object parameter) { parameter = new Object(); // original object from the callee would be unaffected. } public void DoSomething(ref object parameter) { parameter = new Object(); // original object would be a new object }
请参阅文章: Jon Skeet在C#中传递参数
在C#中,引用类型对象的地址按值传递,当使用ref
关键字时,可以为原始对象分配新对象或null,而不使用ref
关键字。
请考虑以下示例:
class Program { static void Main(string[] args) { Object obj1 = new object(); obj1 = "Something"; DoSomething(obj1); Console.WriteLine(obj1); DoSomethingCreateNew(ref obj1); Console.WriteLine(obj1); DoSomethingAssignNull(ref obj1); Console.WriteLine(obj1 == null); Console.ReadLine(); } public static void DoSomething(object parameter) { parameter = new Object(); // original object from the callee would be unaffected. } public static void DoSomethingCreateNew(ref object parameter) { parameter = new Object(); // original object would be a new object } public static void DoSomethingAssignNull(ref object parameter) { parameter = null; // original object would be a null } }
输出将是:
Something System.Object True
通过ref传递变量允许函数将该变量重新指向另一个对象,或者确实为null:例如
object parameter = new object(); FailedChangeRef(parameter); // parameter still points to the same object ChangeRef(ref parameter); // parameter now points to null public void FailedChangeRef(object parameter) { parameter = null; // this has no effect on the calling variable } public void ChangeRef(ref object parameter) { parameter = null; }
参数传递ByVal:描述按值传递参数,这意味着过程不能修改变量本身。
参数传递ByRef:描述通过引用传递参数,这意味着该过程可以修改变量本身。
在C#中,方法参数的默认机制是Pass by Value 。 因此,如果你宣布一个像这样的方法,
public void DoSomething(object parameter){} // Pass by value
因此,创建了对象的新副本,因此对参数的更改不会影响传入的原始对象。
但是,当你通过ref传递参数时,它是Pass by Reference
public void DoSomething(ref object parameter) // Pass by reference
现在,您正在对最初传递的对象上的地址进行操作。 因此,对方法内部参数进行的更改将影响原始对象。
当你看到ref object
意味着,参数必须是object
类型。
您可以阅读文档:
当forms参数是引用参数时,方法调用中的相应参数必须包含关键字ref,后跟与forms参数相同类型的变量引用(第5.3.3节)。 必须明确赋值变量才能将其作为参考参数传递。