可能重复:
如何通过“引用”分配给 c# 中的类字段?
大家好 - 告诉我如何进行这项工作?基本上,我需要一个整数引用类型(int* 可以在 C++ 中工作)
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,只需要引用所需的整数。