ReactiveUI ObservableAsPropertyHelper throws无法转换为类型异常

时间:2013-02-01 12:39:12

标签: reactiveui

我正在尝试使用ObservableAsPropertyHelper来设置一个只读属性,但无论我尝试什么,我似乎都无法按预期工作。

我可以将它提炼成单个测试(使用ReactiveUI 4.3.2.0,Nunit.Framework和Should,全部来自NuGet)

[TestFixture]
public class ObservableAsPropertyHelperTests : ReactiveObject 
{
    private bool _Updated;

    public bool Updated
    {
        get { return _Updated; }
        set { this.RaiseAndSetIfChanged(x => x.Updated, value); }
    }

    [Test]
    public void ShouldSetProperty()
    {
        var input = new Subject<bool>();
        var propertyHelper = input.ToProperty(
                source: this, 
                property: x => x.Updated);//Exception here 

        input.OnNext(true);

        this.Updated.ShouldBeTrue();
    }

但这会导致

System.ArgumentException : Object of type 'ReactiveUI.ObservableAsPropertyHelper`1[System.Boolean]' cannot be converted to type 'System.Boolean'.
   at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
   at System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
   at System.Reflection.RtFieldInfo.InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, Boolean doVisibilityCheck, Boolean doCheckConsistency)
   at System.Reflection.RtFieldInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
   at ReactiveUI.OAPHCreationHelperMixin.ToProperty[TObj,TRet](IObservable`1 This, TObj source, Expression`1 property, TRet initialValue, IScheduler scheduler, Boolean setViaReflection) in y:\Dropbox\ReactiveUI_External\ReactiveUI\ObservableAsPropertyHelper.cs:line 184#0
   at RxUILearning.ObservableAsPropertyHelperTests.ShouldSetProperty() in C:\Dev\RxUILearning\ObservableAsPropertyHelperTests.cs:line 45#1

我可以验证传递给

的参数
    //   source:
    //     The ReactiveObject that has the property
    //
    //   property:
    //     An Expression representing the property (i.e.  'x => x.SomeProperty'

在浏览GitHub上的源代码后,我可以通过调用

来查看
var propertyHelper = input.ToProperty(source: this, property: x => x.Updated, setViaReflection:false);

我的代码避免了异常,但也未通过测试。

如何避免做错了 TM

1 个答案:

答案 0 :(得分:2)

_Updated实际上应该是ObservableAspropertyHelper

[TestFixture]
public class ObservableAsPropertyHelperTests : ReactiveObject 
{
    private ObservableAsPropertyHelper<bool> _Updated;

    public bool Updated
    {
        get { return _Updated.Value; }
    }

    [Test]
    public void ShouldSetProperty()
    {
        var input = new Subject<bool>();
        input.ToProperty(
                source: this, 
                property: x => x.Updated);//Now should work

        input.OnNext(true);

        this.Updated.ShouldBeTrue();
    }