如何在C#中存储对整数的引用?

可能重复:
如何通过“引用”将其分配给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,只需要引用所需的整数。

您不能直接存储对这样的整数的引用,但您可以存储对包含它的GlorifiedInt对象的引用。 在你的情况下,我可能做的是使BitAccessor类嵌套在GlorifiedInt (以便它可以访问私有字段),然后在创建它时向它传递一个引用,然后它可以用来访问m_val领域。 这是一个可以满足您需求的示例:

 class Program { static void Main(string[] args) { var g = new GlorifiedInt(7); g.Bits[0] = false; Console.WriteLine(g.Value); // prints "6" } } class GlorifiedInt { private int m_val; public GlorifiedInt(int value) { m_val = value; } public int Value { get { return m_val; } } public BitAccessor Bits { get { return new BitAccessor(this); } } public class BitAccessor { private GlorifiedInt gi; public BitAccessor(GlorifiedInt glorified) { gi = glorified; } public bool this[int index] { get { if (index < 0 || index > 31) throw new IndexOutOfRangeException("BitAcessor"); return (1 & (gi.m_val >> index)) == 1; } set { if (index < 0 || index > 31) throw new IndexOutOfRangeException("BitAcessor"); if (value) gi.m_val |= 1 << index; else gi.m_val &= ~(1 << index); } } } } 

您不需要引用整数 – 只需将整数放在引用类型中 – 这几乎就是您已经完成的操作。 只需改变这一行:

 Console.WriteLine(foo); 

至:

 Console.WriteLine(bar.Value); 

然后向类Bar添加适当的访问器,并删除编译错误(删除ref关键字)。

另一种方法是通过引用将整数传递给函数:

 static void AddOne(ref int i) { i++; } static void Main() { int foo = 7; AddOne(ref foo); Console.WriteLine(foo); } 

输出:

 8 

你没有指明你反对不安全的代码,所以这应该工作:

 unsafe class Bar { private int* m_ref; public Bar(int* val) { m_ref = val; } public void AddOne() { *m_ref += 1; } } unsafe class Program { static void Main() { int foo = 7; Bar b = new Bar(&foo); b.AddOne(); Console.WriteLine(foo); // prints 8 Console.ReadLine(); } } 

我从来没有在C#中使用指针,但它似乎工作。 我只是不确定可能的副作用是什么。

这不能直接回答你的问题,但你能不能只使用System.Collections.BitArray类?

只是想知道你是否“重新发明轮子”?