事件只能出现在+=或-=的左侧



在Visual Studio 2015中,当我尝试运行以下代码时,出现CS0079编译错误:

public delegate void CostumeLOD(AvatarCustomization costume);
public event CostumeLOD OnCostumeLOD
        {
            add
            {
                CostumeLOD costumeLOD01 = this.OnCostumeLOD;
                CostumeLOD costumeLOD02;
                do
                {
                    costumeLOD02 = costumeLOD01;
                    costumeLOD01 = Interlocked.CompareExchange(ref this.OnCostumeLOD, (CostumeLOD)Delegate.Combine(costumeLOD02, value), costumeLOD01);
                }
                while (costumeLOD01 != costumeLOD02);
            }
            remove
            {
                CostumeLOD costumeLOD01 = this.OnCostumeLOD;
                CostumeLOD costumeLOD02;
                do
                {
                    costumeLOD02 = costumeLOD01;
                    costumeLOD01 = Interlocked.CompareExchange(ref this.OnCostumeLOD, (CostumeLOD)Delegate.Remove(costumeLOD02, value), costumeLOD01);
                }
                while (costumeLOD01 != costumeLOD02);
            }
        }

事件"OnCostumeLOD"只能出现在+=' or-='operator 的左侧

有人能帮我找到解决这个错误的方法吗?

我不相信显式实现event在这里确实是必要的。您似乎试图使其线程安全,但编译器提供的实现已经在这方面做了合理的工作。

也就是说,如果你想让代码工作,你需要为事件声明你自己的支持字段。例如:

private CostumeLOD _onCostumeLOD;
public event CostumeLOD OnCostumeLOD
{
    add
    {
        CostumeLOD costumeLOD01 = this._onCostumeLOD;
        CostumeLOD costumeLOD02;
        do
        {
            costumeLOD02 = costumeLOD01;
            costumeLOD01 = Interlocked.CompareExchange(ref this._onCostumeLOD, (CostumeLOD)Delegate.Combine(costumeLOD02, value), costumeLOD01);
        }
        while (costumeLOD01 != costumeLOD02);
    }
    remove
    {
        CostumeLOD costumeLOD01 = this._onCostumeLOD;
        CostumeLOD costumeLOD02;
        do
        {
            costumeLOD02 = costumeLOD01;
            costumeLOD01 = Interlocked.CompareExchange(ref this._onCostumeLOD, (CostumeLOD)Delegate.Remove(costumeLOD02, value), costumeLOD01);
        }
        while (costumeLOD01 != costumeLOD02);
    }
}


注意:我并不声称以上内容是否真的解决了您试图解决的线程安全问题。我只是提供如何编译它的建议

相关内容

  • 没有找到相关文章

最新更新