| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ObservableObjectPropertyAccess.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Concurrent; |
| | | 9 | | using System.Linq.Expressions; |
| | | 10 | | using System.Reflection; |
| | | 11 | | |
| | | 12 | | #pragma warning disable IDE0130 // Namespace does not match folder structure |
| | | 13 | | namespace MyNet.Observable; |
| | | 14 | | #pragma warning restore IDE0130 // Namespace does not match folder structure |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Cached compiled property getters for <see cref="ObservableObject"/> instances (startup / attach paths only). |
| | | 18 | | /// </summary> |
| | | 19 | | internal static class ObservableObjectPropertyAccess |
| | | 20 | | { |
| | 3 | 21 | | private static readonly ConcurrentDictionary<(Type Type, string PropertyName), Func<ObservableObject, object?>> Gett |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Gets the current value of a public instance property by name. |
| | | 25 | | /// </summary> |
| | | 26 | | public static object? GetPropertyValue(ObservableObject instance, string propertyName) |
| | | 27 | | { |
| | 42 | 28 | | ArgumentNullException.ThrowIfNull(instance); |
| | 42 | 29 | | ArgumentException.ThrowIfNullOrWhiteSpace(propertyName); |
| | | 30 | | |
| | 42 | 31 | | var key = (instance.GetType(), propertyName); |
| | | 32 | | |
| | 42 | 33 | | var getter = GetterCache.GetOrAdd(key, static x => CreateGetter(x.Type, x.PropertyName)); |
| | | 34 | | |
| | 42 | 35 | | return getter(instance); |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | private static Func<ObservableObject, object?> CreateGetter(Type type, string propertyName) |
| | | 39 | | { |
| | 12 | 40 | | var property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public); |
| | | 41 | | |
| | 12 | 42 | | if (property?.CanRead != true || property.GetIndexParameters().Length != 0) |
| | 0 | 43 | | return static _ => UnknownValue.Instance; |
| | | 44 | | |
| | 12 | 45 | | var parameter = Expression.Parameter(typeof(ObservableObject)); |
| | | 46 | | |
| | 12 | 47 | | var cast = Expression.Convert(parameter, type); |
| | | 48 | | |
| | 12 | 49 | | var propertyAccess = Expression.Property(cast, property); |
| | | 50 | | |
| | 12 | 51 | | var convert = Expression.Convert(propertyAccess, typeof(object)); |
| | | 52 | | |
| | 12 | 53 | | return Expression.Lambda<Func<ObservableObject, object?>>(convert, parameter).Compile(); |
| | | 54 | | } |
| | | 55 | | } |
| | | 56 | | |