【问题标题】:A property or indexer may not be passed as an out or ref parameter error属性或索引器不能作为 out 或 ref 参数错误传递
【发布时间】:2016-01-19 19:53:57
【问题描述】:

我的视图模型绑定到来自 WCF 服务的对象。使用ObservableObject.Set<> 时。我收到以下错误:

// Error: A property or indexer may not be passed as an out or ref parameter.
public string SomeProperty
{
    get { return _wcfObject.SomeProperty; }
    set { Set(nameof(SomeProperty), ref _wcfObject.SomeProperty, value); }
}

现在显然我不能这样做,而且这些尝试的变通办法也不起作用。

// Error: } expected
public string SomeProperty
{
    get { return _wcfObject.SomeProperty; }
    set { 
            ref string v = _wcfObject.SomeProperty;
            Set(nameof(SomeProperty), ref v, value); 
        }
}

// Compiles, but property not updated.
public string SomeProperty
{
    get { return _wcfObject.SomeProperty; }
    set { 
            var v = _wcfObject.SomeProperty;
            Set(nameof(SomeProperty), ref v, value); 
        }
}

如何在不从 WCF 服务包装对象的情况下使用 MVVMLight 进行这项工作?

【问题讨论】:

  • 你的属性确实是一个方法。这就是为什么你不能将它作为ref 传递。
  • 你可能会觉得这个question (and answer)很有启发性。

标签: c# wcf mvvm-light


【解决方案1】:

当然它不会起作用,因为您正在更新局部变量v 并在执行setter 后将其丢弃。

您要么必须手动检查,然后自己发起属性更改事件,要么之后将v 分配给_wcfObject.SomeProperty

public string SomeProperty
{
    get { return _wcfObject.SomeProperty; }
    set { 
            var v = _wcfObject.SomeProperty;
            Set(nameof(SomeProperty), ref v, value);
            _wcfObject.SomeProperty = v;
        }
}

这看起来很漂亮……“奇怪”。最好使用适当的支持字段,无论如何在包装模型时直接对模型进行操作都是不好的做法,因为您不能丢弃更改。

private string someField;
public string SomeProperty
{
    get { return someField; }
    set { 
        Set(nameof(SomeProperty), ref someField, value);
    }
}

public ICommand DoSomethingCommand 
{
    return new DelegateCommand(DoSomething);
}

private void DoSomething()
{
    // apply your ViewModel state to the _wcfObject and do something with it
}

然后您的_wcfObject 不受用户所做更改的影响,直到他启动操作/命令。

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 1970-01-01
    • 2019-07-23
    • 2020-11-26
    • 2011-06-16
    • 2012-09-08
    • 2012-07-30
    • 2011-09-23
    相关资源
    最近更新 更多