0

我们认为这将是一种通过值限制绕过结构传递的简单方法(在现实生活中,我们的结构有更多成员)但我们注意到在结构中使用委托不会修改结构内部成员,即使那是委托数组的唯一用途。
鉴于此委托和结构:

public delegate void ChangeValues();

structure Effects
{
    int val1,val2,val3;

    void SetValues(int index)
    {
        ChangeValues[] delegateArray = new ChangeValues(){this.SetValSet1,this.setValSet2,this.SetValSet3};
        delegateArray[index]();  //now set the values as necessary
    }
    void setValSet1()
    {
        val1=0;val2=1;val3=2;
    }        
    void setValSet2()
    {
        val1=1;val2=2;val3=3;
    }        
    void setValSet3()
    {
        val1=2;val2=3;val3=4;
    }        
}

Effects effects = new Effects();
effects.SetValues(1);    //when stepping through code one sees the values change inside eh setValues functions, but the modified values are gone after leaving this function

使用委托会导致结构的另一个实例被创建然后丢失吗?

4

1 回答 1

1

第一:请不要发布甚至不能编译的代码(除非你问为什么它不能编译)。这只是浪费我们的时间。

第二:是的,代表似乎是结构的值复制,不确定细节,但以下是一个解决方案:

public delegate void ChangeValues(ref Effects a);

public struct Effects
{
    int val1,val2,val3;

    public void SetValues(int index)
    {
        ChangeValues[] delegateArray = new ChangeValues[]{setValSet1,setValSet2,setValSet3};
        delegateArray[index](ref this);  //now set the values as necessary
    }
    public void setValSet1(ref Effects a)
    {
        a.val1 = 0; a.val2 = 1; a.val3 = 2;
    }
    public void setValSet2(ref Effects a)
    {
        a.val1 = 1; a.val2 = 2; a.val3 = 3;
    }
    public void setValSet3(ref Effects a)
    {
        a.val1 = 2; a.val2 = 3; a.val3 = 4;
    }
    public override string ToString()
    {
        return val1 + "," + val2 + "," + val3;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Effects effects = new Effects();
        Effects effects2 = new Effects();
        effects.SetValues(1);    //when stepping through code one sees the values change inside eh setValues functions, but the modified values are gone after leaving this function
        Console.WriteLine(effects);
    }
}

它输出:1,2,3

于 2012-09-25T04:46:43.917 回答