在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
的值。请提供您看到的演示行为。