[英]Observe ReactiveObject.Changed of inherited class may or may not work
我嘗試創建一個繼承自 ReactiveObject 的基礎 class。 此 class 需要檢查是否有任何屬性(包括進一步繼承的屬性)已更改。
我的主要問題是,我無法獲得任何可靠的測試結果。 提供的測試可能是綠色的,使用 VS Live Unit Testing 運行它。 把它變成紅色。 將測試項目中的類移到庫中可能會也可能不會使這個測試變綠。
到目前為止,保持它綠色的唯一方法是在繼承的 class 中取消注釋此行。
// Changed.Subscribe(Console.WriteLine);
[TestClass]
public class StateBaseTests
{
#region Tests
[TestMethod]
public void State_ChangesToChanged_PropertyChanged()
{
var _item = new MyTest();
_item.Surname = "Testname";
Assert.AreEqual(Statetype.Changed, _item.State);
}
#endregion
#region SubClasses
public enum Statetype
{
Added,
Changed,
Deleted,
Detached,
Unchanged
}
public abstract class StateBase : ReactiveObject
{
protected StateBase()
{
State = Statetype.Unchanged;
Changed.Select(prop => prop.PropertyName)
.Subscribe(UpdateZustand);
}
protected void UpdateZustand(string propertyName)
{
if(State == Statetype.Unchanged)
State = Statetype.Changed;
}
[Reactive]
public Statetype State { get; set; }
}
private class MyTest : StateBase
{
public MyTest()
{
// Changed.Subscribe(Console.WriteLine);
}
[Reactive]
public string Name { get; set; }
[Reactive]
public string Surname { get; set; }
}
}
這是您的樣本的輕微改編。 使用 VS Mac Community 和 NUnit 完成的。 每次在我的機器上測試都會變成綠色。 如您所見,還打印了屬性名稱。 在我的控制台上它輸出:
State
Surname
這是代碼:
using System;
using System.Reactive.Linq;
using NUnit.Framework;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace Testy {
[TestFixture]
public class Test {
[Test]
public void State_ChangesToChanged_PropertyChanged() {
var _item = new MyTest();
_item.Surname = "Testname";
Assert.AreEqual(Statetype.Changed, _item.State);
}
}
public enum Statetype {
Added,
Changed,
Deleted,
Detached,
Unchanged
}
public abstract class StateBase : ReactiveObject {
protected StateBase() {
State = Statetype.Unchanged;
Changed
.Select(prop => prop.PropertyName)
.Subscribe(
name => {
UpdateZustand(name);
Console.WriteLine(name);
});
}
protected void UpdateZustand(string propertyName) {
if (State == Statetype.Unchanged)
State = Statetype.Changed;
}
[Reactive]
public Statetype State { get; set; }
}
public class MyTest : StateBase {
[Reactive]
public string Name { get; set; }
[Reactive]
public string Surname { get; set; }
}
}
不確定這是否有幫助,但嘗試一下很有趣:)。
PS:這些是使用的 package 版本:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.