C# - 通过引用传递值类型的好而灵活的方法? [英] C# - Good and flexible way to pass value types by reference?

查看:25
本文介绍了C# - 通过引用传递值类型的好而灵活的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题,缩小到一个简单的解释,如下:我有一个类需要使用一个可能会更改的数字(不更改它).这个数字不一定来自另一个类,它可以是任何东西.但是我只想将它交给"一次类,而不是不断地调用更新方法或创建一个包装器(再次,正如我所说,这应该适用于任何类型的数字并且必须包装一切都有些不切实际).

My problem, narrowed down to a simple explaination, is the following: I have a class which needs to work with a number (without changing it) which is subject to change. This number doesn't necessarily come from another class, and it can be anything. But I'd like to only "give" it to the class once, instead of constantly having to call update methods or having to create a wrapper (since again, as I said, this should work with any kind of number and having to wrap up everything is kind of unpratical).

这里有一些代码,希望能帮到你:

Here's some code, hoping it helps:

public class SimpleExample
{
    int value;
    public SimpleExample(int variableOfWhichINeedAReference)
    {
        //Of course this won't work, but I'll keep it simple.
        value = variableOfWhichINeedAReference; 
    }
    public void DisplayValue()
    {
        print(value);
    }
}
public class RandomClass
{
    int myValue = 10;
    SimpleExample s = new SimpleExample(myValue);

    public void WorkWithValue()
    {
        myValue++;
    }

    public void Display()
    {
        print(foo);
        print(bar);
        s.DisplayValue();
    }

}

现在,问题似乎很明显:如果我实例化一个 SimpleExample 并给它一个变量作为参数,它将获得它的值而不是对它的引用.有没有足够简单的方法可以避免我创建包装器?谢谢.

Now, the problem seems pretty obvious: If I instantiate a SimpleExample and give it a variable as a parameter, it will get its value rather than a reference to it. Is there a simple enough way that can avoid me the creation of a wrapper? Thanks.

推荐答案

制作一个非常简单的类:

Make a really simple class:

class Ref<T>
{
    public T Value;
    public Ref<T>()
    {
    }
    public Ref<T>(T value)
    {
        this.Value = value;
    }
}

然后像这样使用它:

class A
{
    Ref<int> x;
    public A(Ref<int> x)
    {
        this.x = x;
    }
    public void Increment()
    {
        x.Value++;
    }
}

...

Ref<int> x = new Ref<int>(7);
A a = new A(x);
a.Increment();
Debug.Assert(x.Value == 8);

请注意,这里的 Ref 类是对 的引用,而不是对 变量 的引用.如果您想引用变量,请使用 Eric Lippert 的解决方案(正如 Filip 指出的那样).

Note that the Ref<T> class here is a reference to a value - not a reference to a variable. If you want a reference to a variable, use Eric Lippert's solution (as pointed out by Filip).

这篇关于C# - 通过引用传递值类型的好而灵活的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆