Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C#中,如何返回对象的属性所引用的内容?_C#_.net_Oop_Reference - Fatal编程技术网

在C#中,如何返回对象的属性所引用的内容?

在C#中,如何返回对象的属性所引用的内容?,c#,.net,oop,reference,C#,.net,Oop,Reference,让我解释一下我的意思。说我有个目标 public class Foo { public int Val { get; set; } } 还有一个 public class Bar { public Foo Reference { get; set; } } 假设我有 Bar mybar = new Bar() { Reference = new Foo() { Val = 69 } } 我想暂时设置 mybar.Reference = null; 然后将其设置回以前的

让我解释一下我的意思。说我有个目标

public class Foo
{
    public int Val { get; set; }
}
还有一个

public class Bar 
{
     public Foo Reference { get; set; }
}
假设我有

Bar mybar = new Bar() { Reference = new Foo() { Val = 69 } }
我想暂时设置

mybar.Reference = null;
然后将其设置回以前的状态。嗯,我做不到

var temp = mybar.Reference;
mybar.Reference = null;
mybar.Reference = temp;

因为上述第2行将
temp
设置为
null
。那么我该如何做我想做的事呢?

不,你可以做,它会起作用的

引用类型,就像您的
Foo
一样,只包含对实际对象的“引用”。所以属性
Bar.Reference
包含
Foo
的实际对象的内存地址

您的代码:

var temp = mybar.Reference;
上面的代码将“内存地址/引用”复制到变量temp
现在
temp
mybar.Reference
都指向内存中的同一对象

mybar.Reference = null;
上面的代码将变量mybar.Reference设置为null,现在mybar.Reference指向“无处”,但请注意,temp仍有对原始对象的引用

mybar.Reference = temp;

最后一行将“内存地址”从
temp
复制回
mybar.Reference

“因为上面的第2行将temp设置为null”-什么?-<代码>mybar.Reference=null无法更改
temp
的值。请提供您看到的演示行为。