| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="PropertyValueAccess.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Reflection; |
| | | 9 | | |
| | | 10 | | namespace MyNet.Observable.Behaviors; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Safe property reads for behavior initialization while derived constructors may still be running. |
| | | 14 | | /// </summary> |
| | | 15 | | internal static class PropertyValueAccess |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Tries to read a property value without surfacing exceptions from getters that depend on uninitialized state. |
| | | 19 | | /// </summary> |
| | | 20 | | public static bool TryGetValue(object target, PropertyInfo property, out object? value) |
| | | 21 | | { |
| | 996 | 22 | | ArgumentNullException.ThrowIfNull(target); |
| | 996 | 23 | | ArgumentNullException.ThrowIfNull(property); |
| | | 24 | | |
| | | 25 | | try |
| | | 26 | | { |
| | 996 | 27 | | value = property.GetValue(target); |
| | 870 | 28 | | return true; |
| | | 29 | | } |
| | 126 | 30 | | catch (Exception ex) when (IsBenignGetterFailure(ex)) |
| | | 31 | | { |
| | 126 | 32 | | value = null; |
| | 126 | 33 | | return false; |
| | | 34 | | } |
| | 996 | 35 | | } |
| | | 36 | | |
| | | 37 | | private static bool IsBenignGetterFailure(Exception exception) |
| | 252 | 38 | | => exception is NullReferenceException or InvalidOperationException |
| | 252 | 39 | | || (exception is TargetInvocationException { InnerException: { } inner } && IsBenignGetterFailure(inner)); |
| | | 40 | | } |
| | | 41 | | |