我正在尝试使用 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?