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

Jon*_*art 11 c# reference value-type

可能重复:
如何通过"引用"将其分配给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'
   }
 }
Run Code Online (Sandbox Code Playgroud)

我必须使用拳击吗?

编辑: 也许我应该更具体.我正在编写一个BitAccessor类,它只允许访问各个位.这是我想要的用法:

class MyGlorifiedInt
{
   private int m_val;
   ...
   public BitAccessor Bits {
      return new BitAccessor(m_val);
   }
}
Run Code Online (Sandbox Code Playgroud)

用法:

MyGlorifiedInt val = new MyGlorifiedInt(7);
val.Bits[0] = false;     // Bits gets a new BitAccessor
Console.WriteLine(val);  // outputs 6
Run Code Online (Sandbox Code Playgroud)

为了使BitAccessor能够修改m_val,它需要对它进行引用.但是我想在很多地方使用这个BitAccessor,只需要引用所需的整数.

tza*_*man 7

您不能直接存储对这样的整数的引用,但您可以存储对GlorifiedInt包含它的对象的引用.在你的情况下,我可能做的是使BitAccessor类嵌套在内部GlorifiedInt(以便它可以访问私有字段),然后向它传递一个引用this它的时间,然后它可以用来访问该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);
            }
    }
    }
}
Run Code Online (Sandbox Code Playgroud)