本文介绍了我可以在 C# 函数(如 C++)中使用引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,我可以这样做:

In C++ I can do this:

 int flag=0,int1=0,int2=1;
 int &iRef = (flag==0?int1:int2);
 iRef +=1;

导致 int1 递增.

with the effect that int1 gets incremented.

我必须修改一些旧的 c# 代码,如果我能做类似的事情会非常有帮助,但我在想……也许不是.有人吗?

I have to modify some older c# code and it would be really helpful if I could do something similar, but I'm thinking ... maybe not. Anybody?

推荐答案

可以做到这一点——或者至少是与您想要的非常相似——但最好找到另一种方法.例如,您可以将整数包装在一个简单的引用类型中.

You can do it - or at least something very similar to what you want - but it's probably best to find another approach. For example, you can wrap the integers inside a simple reference type.

如果您仍然想这样做,请参阅 Eric Lippert 发布的 Ref<T>此处:

If you still want to do it, see the Ref<T> class posted by Eric Lippert here:

sealed class Ref<T>
{
    private readonly Func<T> getter;
    private readonly 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); } }
}

public class Program
{
    public static void Main()
    {
         int flag=0,int1=0,int2=1;

         Ref<int> iRef = (flag == 0 ?
            new Ref<int>(() => int1, z => { int1 = z; }) :
            new Ref<int>(() => int2, z => { int2 = z; }));

         iRef.Value += 1;

        Console.WriteLine(int1);
    }
}

输出:

1

这篇关于我可以在 C# 函数(如 C++)中使用引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 01:24