开发者

How to store a reference to an integer in C#? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How do I assign by “reference” to a class field in c#?

Hello everyone - tell me how to make this work? Basically, I need an integer reference type (int* would wo开发者_C百科rk in 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'
   }
 }

Do I have to use boxing?

Edit: Perhaps I should have been more specific. I'm writing a BitAccessor class, that simply allows access to individual bits. Here's my desired usage:

class MyGlorifiedInt
{
   private int m_val;
   ...
   public BitAccessor Bits {
      return new BitAccessor(m_val);
   }
}

Usage:

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

For BitAccessor to be able to modify m_val, it needs a reference to it. But I want to use this BitAccessor many places, with just a reference to the desired integer.


You can't store a reference to an integer like that directly, but you can store a reference to the GlorifiedInt object containing it. In your case, what I'd probably do is make the BitAccessor class nested inside GlorifiedInt (so that it gets access to private fields), and then pass it a reference to this when it's created, which it can then use to access the m_val field. Here's an example which does what you're looking for:

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);
            }
    }
    }
}


You don't need to have a reference to an integer - just put your integer inside a reference type - which is almost what you've done already. Just change this line:

Console.WriteLine(foo);

to:

Console.WriteLine(bar.Value);

Then add an appropriate accessor to the class Bar, and remove the compile errors (remove the ref keywords).

An alternative approach is to pass the integer to a function by reference:

static void AddOne(ref int i)
{
    i++;
}

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

Output:

8


You didn't specify you were against unsafe code, so this should work:

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();
    }
}

I've never used pointers in C#, but it appears to work. I'm just not sure what the possible side effects are.


This doesn't directly answer your question, but can you not just use the System.Collections.BitArray class?

Just wondering if you are "re-inventing the wheel"?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜