开发者

Assign a reference of an integer in a class

Is it possible to pass an integer as reference at class initializatio开发者_开发问答n and safe the reference?

class Foo {
    private int _refVal;
    public Foo(ref int val) {
        _refval = val; // saves the value, not the reference
    }
}

I could use pointers, but then I need an unsafe context.


This is not possible.

Instead, you can use a class with a writable property, like this:

class Reference<T> {
    public T Value { get; set; }
    public Reference(T value) { Value = value; }
}


Out of interest, why do you need to do this? One integer equal to 5 is equal to another integer equal to 5: if there is some differentiation you want to make between them, the integer value type shouldn't be used - you'd want a class instead.

This is not a direct answer to your question, but as they say improving an algorithm is better than implementing or improving a flawed one; perhaps if you could give us some more context we can help with your more general problem / task as a whole?

Hope that helps!


Wrap it in a custom class I guess.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜