可能是重复问题:
如何在C#中将引用分配给类字段?
大家好 - 告诉我如何使这个工作?基本上,我需要一个整数引用类型(在C++中可以使用int*)
class Bar
{
private ref int m_ref; // This doesn't exist
public A(ref int val)
{
m_ref = val;
}
public void AddOne()
{
m_ref++;
}
}
class Program
{
static void main()
{
int foo = 7;
Bar b = new Bar(ref foo);
b.AddOne();
Console.WriteLine(foo); // This should print '8'
}
}
我需要使用拳击吗?
编辑: 也许我应该更加具体。我正在编写一个BitAccessor类,它仅允许访问单个位。这是我的期望用法:
class MyGlorifiedInt
{
private int m_val;
...
public BitAccessor Bits {
return new BitAccessor(m_val);
}
}
使用方法:
MyGlorifiedInt val = new MyGlorifiedInt(7);
val.Bits[0] = false; // Bits gets a new BitAccessor
Console.WriteLine(val); // outputs 6
为了让BitAccessor能够修改m_val,它需要对其进行引用。但我希望在多个地方使用这个BitAccessor,只需引用所需的整数即可。
main
生命周期无关的其他类中存储对foo
的引用,那么当main
退出并且包含foo
的堆栈帧被销毁时会发生什么? - tzaman