c# - C#中的引用类型和ref有什么区别?

标签 c# ref

<分区>

ref 类型和 Reference 类型 中,我都可以更改对象的值,那么它们之间有什么区别?

有人提供了 answer但我还是不清楚。

static void Main(string[] args)
{
    myclass o1 = new myclass(4,5);
    Console.WriteLine("value of i={0} and j={1}", o1.i, o1.j); //o/p=4,5

    o1.exaple(ref o1.i, ref o1.j);    //Ref type calling
    Console.WriteLine("value of i={0} and j={1}", o1.i, o1.j);// o/p=2,3
    myclass o2 = o1;
    Console.WriteLine("value of i={0} and j={1}", o2.i, o2.j);  // o/p 2,3
    o1.i = 100;
    o1.j = 200;
    Console.WriteLine("value of i={0} and j={1}", o1.i, o1.j);  //o/p=100,200
    Console.WriteLine("value of i={0} and j={1}", o2.i, o2.j); //o/p=100,200
    Console.ReadKey();
}

public class myclass
{
    public int i;
    public int j;

    public myclass(int x,int y)
    {
        i = x;
        j = y;
    }
    public void exaple(ref int a,ref int b) //ref type
    {
        a = 2;
        b = 3;
    }
}

最佳答案

带有 ref 关键字的参数提供对对象引用的引用,您可以在其中更改此引用在更改后指向的位置

public void TestObject(Person person)
{ 
    person = new Person { Name = "Two" };
}

public void TestObjectByRef(ref Person person)
{ 
    person = new Person { Name = "Two" };
}

然后当你使用那些方法的时候

var person = new Person { name = "One" };

TestObject(person);
Console.WriteLine(person.Name); // will print One

TestObjectByRef(ref person);
Console.WriteLine(person.Name); // will print Two

下面是来自 MSDN 的引述:https://msdn.microsoft.com/en-us/library/14akc2c7.aspx

The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method. For example, if the caller passes a local variable expression or an array element access expression, and the called method replaces the object to which the ref parameter refers, then the caller’s local variable or the array element now refer to the new object.

当您将引用类型作为参数传递给没有 ref 关键字的方法时,对作为副本传递的对象的引用。您可以更改对象的值(属性),但如果将其设置为引用另一个对象,则不会影响原始引用。

关于c# - C#中的引用类型和ref有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522016/

相关文章:

C#线程声明

c# - 用于验证 GSTIN 编号的正则表达式

rust - 将 Ref<Box<dyn Any>> 向下转换为 Ref<Box<T>> 时处理向下转换错误

reactjs - 如何在 Storybook Story 中将焦点设置为输入

C# 'ref' 关键字,性能

javascript - 通过多个元素的单个引用来 react : How to replace . querySelectorAll

c# - 如何使用 backgroundworker 更新 GUI?

c# - 查找多种类型的所有控件?

swift - Firebase 类型 "ViewController"的值没有成员 'ref'

c# - 在 C# 中创建 PowerShell Cmdlet - 管道链