Saving object reference in C #

I was wondering how you can save a reference to an object in .net.

That is, I would like something like the following code (note, of course, that the following code may be detached from how to actually do this):

class Test
{
    private /*reference to*/ Object a;
    public Test(ref int a)
    {
        this.a = a;
        this.a = ((int)this.a) + 1;
    }
    public Object getA() { return this.a; }
}
/*
 * ...
 */
static void Main(string[] args)
{
    int a;
    a=3;
    Test t = new Test(ref a);
    Console.WriteLine(a);
    Console.WriteLine(t.getA());
    Console.ReadKey();
}

To create the following output:

4
4

Ideally, I would like to do this without writing a wrapper class around an integer.

In other words, I think I need pointers in .Net.

+5
source share
2 answers

You cannot store variable references in .NET, period. You can store references to objects, but not reference variables.

, , . , , , .

, , . ( ) "a" " " ( ) "a" " int variable". , int " ", . , , ; ; int .

, , ​​, , , ?

. , , .

, , int, , . , .

, .

void M(ref int y) { y = 123; }
...
int x = 0;
M(ref x);

: "x y - ".

, , , " , , ", :

class Ref<T>
{
    private Func<T> getter;
    private Action<T> setter;
    public Ref(Func<T> getter, Action<T> setter)
    {
        this.getter = getter;
        this.setter = setter;
    }
    public T Value
    {
        get { return getter(); }
        set { setter(value); }
    }
}
...
int abc = 123;
var refabc = new Ref<int>(()=>abc, x=>{abc=x;});
... now you can pass around refabc, store it in a field, and so on
refabc.Value = 456;
Console.WriteLine(abc); // 456
Console.WriteLine(refabc.Value); // 456

?

+36

# , ++ int& a. . - :

class Test
{
    private Func<int> get_a;
    private Action<int> set_a;
    public Test(Func<int> get_a, Action<int> set_a)
    {
        this.get_a = get_a;
        this.set_a = set_a;
        this.set_a(this.get_a() + 1);
    }
    public Object getA() { return this.get_a(); }
}
/*
 * ...
 */
static void Main(string[] args)
{
    int a;
    a=3;
    Test t = new Test(() => a, n => { a = n; });
    Console.WriteLine(a);
    Console.WriteLine(t.getA());
    Console.ReadKey();
}

VS, , , .

+9

All Articles