문제

Is it possible to pass an integer as reference at class initialization 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top