Repository navigation
Tutorial5.en
This section introduces utilities developed during the creation of this library, as well as tools that are useful when using it.
- ResultWithValue
- UniqueOperatorExcuter
- EventListener
- PropertyAccessor
- EqualityComparer
- Comparer
- ReusableCompositeDisposable
ResultWithValue is provided to make Try methods easier to use.
ResultWithValue.cs
public struct ResultWithValue<TValue>{
public bool Result{get;}
public TValue Valule{get;}
public ResultWithValue<TValue> When(Action<TValue>? caseTrue = null, Action<TValue>? caseFalse = null){}
public TOutput When<TOutput>(Func<TValue, TOutput> caseTrue, Func<TValue, TOutput> caseFalse) {}
public ResultWithValue<TValue> EitherWay(Action<TValue> resultAction) {}
public TOutput EitherWay<TOutput>(Func<TValue, TOutput> resultFunc) {}
public static implicit operator Boolean(ResultWithValue<TValue> rwv){}
}Using it, you can write code such as the following.
treenodeA.TryAddChild(nodeX).When(
o => o.TryRemoveChild(nodeY),
x => treenodeB.TryAddChild(x)
);
treenodeC.TryRemoveOwn().When(o => list.Add(o));The following delegates and static methods also allow you to use it with conventional Try methods.
ResultWithValue_Extensions.cs
public delegate bool TryCallback<in TInput, TValue>(TInput input, [MaybeNullWhen(false)] out TValue value);
public delegate bool TryCallback<TValue>([MaybeNullWhen(false)] out TValue value);
public static class ResultWith<TValue>{
public static ResultWithValue<TValue> Of<TInput>(TryCallback<TInput,TValue> tryMethod,TInput input){}
public static ResultWithValue<TValue> Of<TValue>(TryCallback<TValue> tryMethod){}
}The following examples show its use with Dictionary.TryGetValue and Stack.TryPop.
var dic = new Dictionary<string,ItemObj>();
ResultWith<ItemObj>.Of(dic.TryGetValue,"key").When(
o => { },
x => { },
)var stack = new Stack<ItemObj>();
ResultWith<ItemObj>.Of(stack.TryPop).When(
o => { },
x => { },
);This class prevents recursive or duplicate execution of a specified operation.
UniqueOperationExecutor.cs
public class UniqueOperationExecutor{
public void Register(string key, Action action){ }
public IDisposable ExecuteUnique(string key){ }
public IDisposable LateEvalute<TProp>(string key, Func<TProp> getPropertyValue){ }
public IDisposable ExecuteUnique(Action operation){ }
}Use Register to associate a key with an operation.
When the returned IDisposable is disposed, the operation is executed once the last outstanding IDisposable has been disposed.
LateEvaluate executes the operation only if the value returned by getPropertyValue differs between the initial call and the time the last IDisposable is disposed.
ExecuteUnique(Action operation) is also available and does not require prior registration.
A key is not required; instead, operations are identified by the value of operation.Method.MetadataToken.
The following code uses Register to run a timer.
var uniExecutor = new UniqueOperationExecutor();
var sw = new Stopwatch();
Action displayElapsedTime = () => {
Console.WriteLine($"Time {sw.Elapsed.Seconds}.{sw.Elapsed.Milliseconds}(sec)");
};
uniExecutor.Register("keyA", displayElapsedTime);
sw.Start();
var t1 = Task.Run(() => {
var exe = uniExecutor.ExecuteUnique("keyA");
Thread.Sleep(1000);
exe.Dispose();
});
var t2 = Task.Run(() => {
Thread.Sleep(800);
var exe = uniExecutor.ExecuteUnique("keyA");
Thread.Sleep(800);
exe.Dispose();
});
var t3 = Task.Run(() => {
var exe = uniExecutor.ExecuteUnique("keyA");
Thread.Sleep(500);
exe .Dispose();
});
var t4 = Task.Run(() => {
Thread.Sleep(2000);
var exe = uniExecutor.ExecuteUnique("keyA");
Thread .Sleep(500);
exe .Dispose();
});
Task.WaitAll(t1, t2, t3, t4);
//Time 1.621(sec)
//Time 2.537(sec)Because t1, t2, and t3 overlap, the operation is executed when their overlapping period ends.
For operations involving values such as each node's Depth() or Height(),
if you want to compare values before and after a change and execute an operation only when they differ,
use LateEvaluate.
The following code uses LateEvaluate to raise change notifications for the Level property.
public class NotifyLevelChangeNode
: ObservableGeneralTreeNode<NotifyLevelChangeNode> {
UniqueOperationExecutor UniOperator = new UniqueOperationExecutor();
IDisposable reporter;
public NotifyLevelChangeNode() {
//Register action with key
UniOperator.Register(nameof(Level), () => Properties.Notify(nameof(Level)));
//Set initial status
reporter = CreateNewReporter();
this.StructureChanged += (s, e) => {
if (e.IsAncestorChanged) {
//Evaluate whether level changed
reporter.Dispose();
//Reset status
reporter = CreateNewReporter();
}
};
}
IDisposable CreateNewReporter() => UniOperator.LateEvaluate(nameof(Level), () => Level);
public int Level => this.Depth();
public string Name { get; set; }
}The following code subscribes to change notifications for the Level property.
var dic = "ABCDE".ToCharArray().Select(x => x.ToString()).ToDictionary(x => x, x => new NotifyLevelChangeNode() { Name = x });
dic.Values.AssembleAsNAryTree(2);
Console.WriteLine(dic["A"].ToTreeDiagram(x => $"{x.Name}, Level:{x.Level}"));
/*
A, Level:0
├ B, Level:1
│ ├ D, Level:2
│ └ E, Level:2
└ C, Level:1
*/
foreach(var node in dic.Values) {
node.PropertyChanged += (s, e) => {
if(e.PropertyName == "Level" && s is NotifyLevelChangeNode nd) {
Console.WriteLine($"{nd.Name}, Level:{nd.Level}");
}
};
}
dic["A"].AddChild(dic["D"]);
// D, Level:1
dic["C"].AddChild(dic["E"]);
//
Console.WriteLine(dic["A"].ToTreeDiagram(x => $"{x.Name}, Level:{x.Level}"));
/*
A, Level:0
├ B, Level:1
├ C, Level:1
│ └ E, Level:2
└ D, Level:1
*/This class supports subscribing to and unsubscribing from events.
The following code subscribes to nodeA.PropertyChanged and nodeA.StructureChanged, then assembles a tree structure.
var nodeA = new ObservableNamedNode() { Name ="A" };
var listener1 = new EventListener<PropertyChangedEventHandler>(
h => nodeA.PropertyChanged += h,
h => nodeA.PropertyChanged -= h,
(s, e) => Console.WriteLine($"sender:{s}, Property handler1: {e.PropertyName}"));
var listener2 = new EventListener<EventHandler<StructureChangedEventArgs<ObservableNamedNode>>>(
h => nodeA.StructureChanged += h,
h => nodeA.StructureChanged -= h,
(s, e) => Console.WriteLine($"sender:{s}, Structure handler: {e.TreeAction}"));
var listener3 = new EventListener<EventHandler<StructureChangedEventArgs<ObservableNamedNode>>, PropertyChangedEventArgs>(
h => nodeA.StructureChanged += h,
h => nodeA.StructureChanged -= h,
ph => (s, e) => {
if (e.IsAncestorChanged) ph(s, new PropertyChangedEventArgs("Ancestor"));
if (e.IsDescendantChanged) ph(s, new PropertyChangedEventArgs("Descendant"));
},
propHandler);
void propHandler(object? sender, PropertyChangedEventArgs e) {
Console.WriteLine($"sender:{sender}, Structure -> Property handler: {e.PropertyName}");
}
nodeA.AddChild(new ObservableNamedNode() { Name = "B" });
/*
sender:A, Structure handler: Join
sender:A, Structure -> Property handler: Descendant
*/
var nodeS = new ObservableNamedNode() { Name = "S" }.AddChild(nodeA);
/*
sender:A, Property handler1: Parent
sender:A, Structure handler: Join
sender:A, Structure -> Property handler: Ancestor
*/
nodeS.AddChild(new ObservableNamedNode() { Name = "C"});
/*
sender:A, Structure handler: Join
*/
var disposables = new ReusableCompositeDisposable(listener1, listener2, listener3);
disposables.ClearAndDispose();//Unsubscribe
nodeS.Disassemble();
//listener3 subscribes to the StructureChanged event and invokes a handler for NotifyPropertyChanged.
EventListener implements IDisposable and unsubscribes when disposed.
This class helps implement the INotifyPropertyChanged interface.
PropertyAccessor.cs
public class PropertyAccessor {
public PropertyAccessor(object? owner, Func<PropertyChangedEventHandler?> handlerGetter) { }
public PropertyAccessor(object? owner, Action<PropertyChangedEventArgs> raiseAction) { }
public T GetValue<T>(T initialValue = default, [CallerMemberName] string? propertyName = null) { }
public ResultWithValue<PropertyAccessor> TrySetValue<T>(T value, [CallerMemberName] string? propertyName = null) { }
public ResultWithValue<PropertyAccessor> TrySetField<T>(ref T storage, T value, [CallerMemberName] string? propertyName = null) { }
public PropertyAccessor Notify([CallerMemberName] string? propertyName = null) { }
public static PropertyChangedEventArgs GetOrAddCachedEventArgs(string name){ }
}You can avoid declaring backing fields by using TryGetValue and TrySetValue.
If you use a backing field, use the TrySetField method.
Event arguments are cached in a static field to reduce object allocations.
The cache uses ConcurrentDictionary and is thread-safe.
Two constructors are provided.
To implement INotifyPropertyChanged with minimal code,
use PropertyAccessor(object, Func<PropertyChangedEventHandler?>).
public class NotifyObjA : INotifyPropertyChanged {
public NotifyObjA() {
Properties = new PropertyAccessor(this, () => PropertyChanged);
}
protected PropertyAccessor Properties { get; }
public event PropertyChangedEventHandler? PropertyChanged;
}
public class NotifyObjAA : NotifyObjA {
public string FirstName {
get => Properties.GetValue<string>();
set => Properties.TrySetValue(value)
.When(o => o.Notify(nameof(FullName)));
}
public string LastName {
get => Properties.GetValue<string>();
set => Properties.TrySetValue(value)
.When(o => o.Notify(nameof(FullName)));
}
public string FullName => FirstName + " " + LastName;
public int Age {
get => Properties.GetValue(0);
set => Properties.TrySetValue(value);
}
}var objA = new NotifyObjAA() { FirstName = "Leonardo", LastName = "da Vinci" };
Console.WriteLine(objA.FullName);
//Leonardo da Vinci
objA.PropertyChanged += (s, e) => {
if(e.PropertyName == "FullName")
Console.WriteLine($"{(s as NotifyObjAA)?.FullName}");
};
objA.LastName = "DiCaprio";
//Leonardo DiCaprioIf the derived class needs to override a Changed event or a RaiseEvent method,
use PropertyAccessor(object, Action<PropertyChangedEventArgs>).
public class NotifyObjB : INotifyPropertyChanged {
public NotifyObjB() {
Properties = new PropertyAccessor(this, RaisePropertyChangedEvent);
}
protected PropertyAccessor Properties { get; }
protected virtual void RaisePropertyChangedEvent(PropertyChangedEventArgs e) {
PropertyChanged?.Invoke(this, e);
}
public virtual event PropertyChangedEventHandler? PropertyChanged;
}
public class NotifyObjBB : NotifyObjB {
string _firstName = "";
string _lastName = "";
public NotifyObjBB(string firstname, string lastname) {
_firstName = firstname;
_lastName = lastname;
}
public string FirstName {
get => _firstName;
set => Properties.TrySetField(ref _firstName, value)
.When(o => o.Notify(nameof(FullName)));
}
public string LastName {
get => _lastName;
set => Properties.TrySetField(ref _lastName, value)
.When(o => o.Notify(nameof(FullName)));
}
public string FullName => FirstName + " " + LastName;
protected override void RaisePropertyChangedEvent(PropertyChangedEventArgs e) {
Console.WriteLine($"Raise Event: {e.PropertyName}");
base.RaisePropertyChangedEvent(e);
}
public override event PropertyChangedEventHandler? PropertyChanged {
add {
base.PropertyChanged += value;
Console.WriteLine("Handler added.");
}
remove {
base.PropertyChanged -= value;
Console.WriteLine("Handler removed.");
}
}
}var objB = new NotifyObjBB("Matt", "Reeves");
Console.WriteLine(objA.FullName);
//Matt Reeves
objB.PropertyChanged += (s, e) => {
if (e.PropertyName == "FullName")
Console.WriteLine($"{(s as NotifyObjBB)?.FullName}");
};
//Handler added
objB.FirstName = "Keanu";
/*
Raise Event: FirstName
Raise Event: FullName
Keanu Reeves
*/Equality<T>.ValueOrReference is used when no IEqualityComparer is specified in the initialization methods of ObservableMirrorCollection<T> or ObservableFilterSortMirrorCollection, and internally in ImitableCollection.
Even if a reference type implements IEquatable<T>, as String and HierarchyWrapper do, this comparer forces reference-identity comparison.
Equality.cs
public static class Equality {
/// <summary>Returns a comparer that compares by value if the type is a value type, and by reference if the type is a reference type. </summary>
public static IEqualityComparer ValueOrReference { get; }
}
public static class Equality<T> {
/// <summary>Selects the key for performing equality comparison.</summary>
public static EqualityComparer<T> ComparerBy<TKey>(Func<T, TKey> selector, IEqualityComparer<TKey>? keyComparer = null) { }
/// <summary>Returns a comparer that compares by value if T is a value type, and by reference if T is a reference type.</summary>
public static EqualityComparer<T> ValueOrReference { get; }
}Reverses the result of a comparer.
Comparer.cs
public class InvertibleComparer<T> : Comparer<T> {
/// <summary>Inverts the comparison result. </summary>
public InvertibleComparer<T> Invert() { }
}
public static class ComparerExtensions {
/// <summary>Inverts the comparison result.</summary>
public static InvertibleComparer<T> Invert<T>(this IComparer<T> self) { }
}This was defined to make ReadOnlyObservableFilterSortCollection easier to use.
var lst = new List<string> { "Alvin", "Ben", "Carl", "Daniel", };
var cmpr = Comparer<string>.Create((x, y) => x.Length - y.Length);
var pxyLst = lst.ToObservableFilterSortMirror();
pxyLst.SortBy(x => x, cmpr);
Console.WriteLine(string.Join (", ", pxyLst));
////Ben, Carl, Alvin, Daniel
pxyLst.SortBy(x => x, cmpr.Invert());
Console.WriteLine(string.Join (", ", pxyLst));
////Daniel, Alvin, Carl, BenCombines multiple IDisposable instances so they can be disposed together.
ReusableCompositeDisposable.cs
public class ReusableCompositeDisposable : IEnumerable<IDisposable>, IDisposable {
public ReusableCompositeDisposable(IEnumerable<IDisposable> disposables) { }
public ReusableCompositeDisposable(params IDisposable[] disposables) { }
public ReusableCompositeDisposable() { }
public void ClearAndDispose() { }
public void Add(IDisposable disposable) { }
public void Remove(IEnumerable<IDisposable> disp){ }
}
public static class EnumerableExtensions{
public static IDisposable CombineDisposables<T>(this IEnumerable<T> enumerable) { }
public static IDisposable CombineDisposablesAndSelf<T>(this T disposable)
where T : IEnumerable<IDisposable>, IDisposable { }
}When you need to dispose each item and unsubscribe from collection notifications at the same time, as when working with ObservableMirrorCollection, you can use CombineDisposablesAndSelf().