我可以像使用C ++一个C#函数内的参考? [英] Can I use a reference inside a C# function like C++?

查看:118
本文介绍了我可以像使用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.

如果你仍然想这样做,请参阅参考< 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);
    }
}



输出:

Output:

1

这篇关于我可以像使用C ++一个C#函数内的参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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