题
考虑我的第一次尝试,一个简单的类型F#如下所示:
type Test() =
inherit BaseImplementingNotifyPropertyChangedViaOnPropertyChanged()
let mutable prop: string = null
member this.Prop
with public get() = prop
and public set value =
match value with
| _ when value = prop -> ()
| _ ->
let prop = value
this.OnPropertyChanged("Prop")
现在我通过C#测试此(此对象被暴露于C#项目,所以表观C#语义是期望的):
[TestMethod]
public void TaskMaster_Test()
{
var target = new FTest();
string propName = null;
target.PropertyChanged += (s, a) => propName = a.PropertyName;
target.Prop = "newString";
Assert.AreEqual("Prop", propName);
Assert.AreEqual("newString", target.Prop);
return;
}
propName
被适当地分配,我的F#设定器正在运行,但第二断言失败因为prop
的基本值也不改变。这类品牌的意义,我,因为如果我从mutable
字段中删除prop
,不产生错误(和一个应该是因为我想变异值)。我觉得我必须缺少的基本概念。
什么是重新绑定在prop
类/转变Test
,这样我可以通过我的单元测试的正确方法是什么?
解决方案
尝试这种情况:
type Test() =
inherit BaseImplementingNotifyPropertyChangedViaOnPropertyChanged()
let mutable prop: string = null
member this.Prop
with public get() = prop
and public set value =
match value with
| _ when value = prop -> ()
| _ ->
prop <- value
this.OnPropertyChanged("Prop")
您需要进行结合可变的,然后改变其在二传手的价值。在您最初的代码中,你只是在你的二传手内创建一个新的结合(也称为prop
),所以没有变化是明显的。
其他提示
作为一个侧面说明,我可能会使用代替if .. then
构建match
de,因为它使得代码更简洁(当需要测试的值agains多个复杂的图案patterh匹配是特别有价值的)。此外,public
是member
默认访问,这样可以使代码有点更简洁:
type Test() =
inherit BaseImplementingNotifyPropertyChangedViaOnPropertyChanged()
let mutable prop : string = null
member this.Prop
with get() = prop
and set(value) =
if value <> prop then
prop <- value
this.OnPropertyChanged("Prop")
在你的模式匹配你实际上是结合新值
let prop = value
在绑定使用相同的名称这样的值,它会为影的新范围内的其他值声明的一个。我相信你真的想做的事是这样的:
prop <- value
不隶属于 StackOverflow