【问题标题】:What is the difference between Reference type and ref in C#? [duplicate]C#中的引用类型和引用有什么区别? [复制]
【发布时间】:2017-05-22 04:18:09
【问题描述】:

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

有人提供了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;
    }
}

【问题讨论】:

  • 很简单:就是C中的指针和指向指针的指针的区别。

标签: c# ref


【解决方案1】:

带有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

ref 关键字导致参数通过引用传递,而不是通过 价值。通过引用传递的效果是对 被调用方法中的参数反映在调用方法中。为了 例如,如果调用者传递一个局部变量表达式或一个数组 元素访问表达式,调用的方法替换对象 ref 参数所引用的,然后是调用者的局部变量或 数组元素现在引用新对象。

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

【讨论】:

  • 能否请您详细说明一下,我上周才开始学习 C#
  • "如果您将其设置为引用另一个对象,则不会影响原始引用。"你能写一个简单的例子(代码)来解释一下吗提前谢谢:)
  • 答案中的例子,见TestObject方法的使用
猜你喜欢
  • 2011-01-25
  • 2011-06-30
  • 1970-01-01
  • 2012-02-06
  • 1970-01-01
  • 2012-02-09
  • 2019-09-26
  • 1970-01-01
  • 2010-09-30
相关资源
最近更新 更多