我想如果我可以做一个引用,总是指向该特定变量,而不是指向该变量当前表示的对象(或更准确地说是内存位置)。参考变量,而不是对象
举一个例子,假设我有以下程序,我想创建一个对MyClass a的引用,以便始终返回MyClass a中的任何值,即使该值发生更改。我有一些看起来像的代码。
class MyClass
{
public int value = 0;
}
class Program
{
static MyClass saved; //maintained and used by the following two functions
static void StoreReference(MyClass input)
{
saved = input;
}
static void SetValue()
{
saved.value = 42;
}
static void Main(string[] args)
{
//A couple arbitrary classes I'd like to have references to
MyClass a = new MyClass();
MyClass b = new MyClass();
StoreReference(a);
a = b;
SetValue();
Console.Write(a.value); //should print 42, instead prints 0 since it reads in the original object a was set to
}
}
是否有任何可以在C#做到这一点,或者任何可以防止被分配给一个新的存储位置的变量(以使上面的代码将在返回错误= b)的?
,你可以将它定义为只读 – dotctor
做你试着做StoreReference(REF MyClass的输入) –
用只读的问题是,我希望能够说a.value中= 42而不是=新MyClass的()因为第二个示例更改了指向的内存位置。 – user3875080