使用ref object par和不使用ref object par的2种方法之间有什么区别? [英] What is the difference between 2 methods with ref object par and without?

查看:51
本文介绍了使用ref object par和不使用ref object par的2种方法之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下方法在引用对象参数方面有什么区别:

I wonder what the difference is between the following methods with regards to how the object parameter is referenced:

public void DoSomething(object parameter){}

public void DoSomething(ref object parameter){}

如果我想将对 object 的引用更改为不覆盖同一引用中的对象,我应该使用 ref对象参数吗?

Should I use ref object parameter in cases where I want to change the reference to the object not override the object in the same reference?

推荐答案

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 不可能的关键字.

In C#, Reference type object's address is passed by value, when the ref keyword is used then the original object can be assigned a new object or null, without ref keyword that is not possible.

考虑以下示例:

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 object par和不使用ref object par的2种方法之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆