refactor: Clean up ReflectionHelper a bit
* Rename '(static_)property_delegates_of_type' -> '(static_)property_getters', and include name w/ prop getters * Rename 'FindApplicableConstructor' -> 'get_constructor' * Remove unused fns
This commit is contained in:
1 parent
9c5ac2eb19
commit
bed44db642
13 files changed
+52
-132
No files matched your search
@@ -77,8 +77,8 @@
|
||||
public IRaiseCanExecuteChangedCommand vol_shift { get; }
|
||||
|
||||
IEnumerable<IRaiseCanExecuteChangedCommand> _commands =>
|
||||
ReflectionHelper.property_delegates_of_type<VolSurfaceMacroActionsVM, IRaiseCanExecuteChangedCommand>()
|
||||
.Select(g => g(this));
|
||||
ReflectionHelper.property_getters<VolSurfaceMacroActionsVM, IRaiseCanExecuteChangedCommand>()
|
||||
.Select(pg => pg.get(this));
|
||||
|
||||
public void selection_changed(IEnumerable<VolSurfaceDisplayGridExpiration> selected) {
|
||||
_selected_exps = selected.ToList();
|
||||
|
||||
@@ -137,8 +137,8 @@ namespace bts.shell.market_view {
|
||||
}
|
||||
|
||||
public static IEnumerable<GridColumnSettings> all =>
|
||||
ReflectionHelper.static_property_delegates_of_type<GridColumnSettings>(typeof(DefaultColumns))
|
||||
.Select(g => g());
|
||||
ReflectionHelper.static_property_getters<GridColumnSettings>(typeof(DefaultColumns))
|
||||
.Select(pg => pg.get());
|
||||
|
||||
static GridColumnSettings _mk(Columns key, string display_name = null, double width = 80, bool is_visible = true, Color? fg = null, Color? bg = null, HorizontalAlignment h_align = HorizontalAlignment.Right) =>
|
||||
new(col_id(key), display_name, is_visible, font_color_override: fg, width: width, horizontal_alignment: h_align, background_color_override: bg);
|
||||
|
||||
@@ -47,8 +47,8 @@ namespace mbts.spark {
|
||||
/// Viewmodel class designed for <see cref="ui.spark.MarketViewView"/>
|
||||
/// </summary>
|
||||
partial class MarketViewVM : DisposableViewModelBase, IHandleRowSelection {
|
||||
static readonly IReadOnlyList<Func<MarketViewVM, IDataGridColumnFilter<Row>>> _filter_getters =
|
||||
ReflectionHelper.property_delegates_of_type<MarketViewVM, IDataGridColumnFilter<Row>>().ToReadOnlyList();
|
||||
static readonly IEnumerable<Func<MarketViewVM, IDataGridColumnFilter<Row>>> _filter_getters =
|
||||
ReflectionHelper.property_getters<MarketViewVM, IDataGridColumnFilter<Row>>().Cut2();
|
||||
|
||||
static readonly IComparer<SecurityMD> _sec_md_key_comparer = Comparer<uint>.Default.wrap(SecurityMD.key_fn);
|
||||
static readonly IComparer<Row> _row_key_comparer = _sec_md_key_comparer.wrap<SecurityMD, Row>(r => r.security_md);
|
||||
|
||||
@@ -132,8 +132,8 @@ namespace bts.shell.time_and_sales {
|
||||
}
|
||||
|
||||
public static IEnumerable<GridColumnSettings> all =>
|
||||
ReflectionHelper.static_property_delegates_of_type<GridColumnSettings>(typeof(DefaultColumns))
|
||||
.Select(g => g());
|
||||
ReflectionHelper.static_property_getters<GridColumnSettings>(typeof(DefaultColumns))
|
||||
.Select(pg => pg.get());
|
||||
|
||||
static GridColumnSettings _mk_col(
|
||||
ColKey key,
|
||||
|
||||
@@ -281,8 +281,8 @@
|
||||
}
|
||||
|
||||
IEnumerable<IDataGridColumnFilter<TimeAndSalesRowVM>> _filters =>
|
||||
ReflectionHelper.property_delegates_of_type<TimeAndSalesVM, IDataGridColumnFilter<TimeAndSalesRowVM>>()
|
||||
.Select(fn => fn(this));
|
||||
ReflectionHelper.property_getters<TimeAndSalesVM, IDataGridColumnFilter<TimeAndSalesRowVM>>()
|
||||
.Select(pg => pg.get(this));
|
||||
|
||||
public (TimeAndSalesFilterSettings filters, IReadOnlyList<SortingCriteria> sorting_criteria, GridSettings grid_settings) create() =>
|
||||
(_get_filter_states(), _sorting_criteria, grid_settings_manager.create());
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ namespace mbts.ui.spark {
|
||||
if (pvm is IAlgoParamVM<QuantityMeasureImmutable?>) return QuantityMeasureTemplate;
|
||||
if (pvm is IAlgoParamVM<ExecutionStrategy>) return ExecutionStrategyTemplate;
|
||||
if (pvm is IAlgoParamVM<Google.Protobuf.WellKnownTypes.Timestamp>) return TimestampTemplate;
|
||||
var targ = ReflectionHelper.GetGenericTypeArgs(pvm.GetType(), generic_algo_param_itype).FirstOrDefault();
|
||||
var targ = ReflectionHelper.get_generic_type_args(pvm.GetType(), generic_algo_param_itype).FirstOrDefault();
|
||||
if (targ != null) {
|
||||
if (targ.IsEnum)
|
||||
return EnumTemplate;
|
||||
|
||||
@@ -39,8 +39,9 @@
|
||||
using SecurityType = api.Security.ContractOneofCase;
|
||||
|
||||
class PNLVM : DisposableViewModelBase, IHandleRowSelection {
|
||||
static readonly IReadOnlyList<Func<PNLVM, IDataGridColumnFilter<PNLRowData>>> _filter_getters =
|
||||
ReflectionHelper.property_delegates_of_type<PNLVM, IDataGridColumnFilter<PNLRowData>>().ToReadOnlyList();
|
||||
static readonly IEnumerable<Func<PNLVM, IDataGridColumnFilter<PNLRowData>>> _filter_getters =
|
||||
ReflectionHelper.property_getters<PNLVM, IDataGridColumnFilter<PNLRowData>>().Cut2();
|
||||
|
||||
static readonly TimeSpan _auxiliary_grid_update_throttle = TimeSpan.FromSeconds(0.2);
|
||||
// delegates
|
||||
static readonly Func<OrderSecurityRootPair, PNLKey> _order_pnl_key_fn = o => new PNLKey(o.order.order.account_id(), o.order.order.security_key());
|
||||
|
||||
@@ -119,8 +119,8 @@ namespace Spark.Trading {
|
||||
}
|
||||
|
||||
public static IEnumerable<GridColumnSettings> all =>
|
||||
ReflectionHelper.static_property_delegates_of_type<GridColumnSettings>(typeof(DefaultColumns))
|
||||
.Select(g => g());
|
||||
ReflectionHelper.static_property_getters<GridColumnSettings>(typeof(DefaultColumns))
|
||||
.Select(pg => pg.get());
|
||||
|
||||
static GridColumnSettings _mk(
|
||||
ColKey key,
|
||||
|
||||
@@ -498,7 +498,7 @@ namespace mbts.ui.utility {
|
||||
|
||||
public class ObservableAutoWrapper<View, Model> : ObservableCollection<View> {
|
||||
private static Func<Model, View> _get_default_converter() {
|
||||
var constructor = ReflectionHelper.FindApplicableConstructor(typeof(View), typeof(Model));
|
||||
var constructor = ReflectionHelper.get_constructor(typeof(View), typeof(Model));
|
||||
if (constructor == null)
|
||||
throw new InvalidOperationException("[{0}] {1} type does not have a public constructor({0})".fmt(typeof(ObservableAutoWrapper<View, Model>), typeof(View), typeof(Model)));
|
||||
return model => (View)constructor.Invoke(new object[] { model });
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
// convert to a hashset for quicker lookups
|
||||
var exclude = new HashSet<string>(except_props);
|
||||
return new PropertyChangeDetector<T>(
|
||||
ReflectionHelper.get_props<T>()
|
||||
ReflectionHelper.properties<T>()
|
||||
.Where(p => !exclude.Contains(p.Name))
|
||||
.Select(p => p.Name)
|
||||
.ToArray());
|
||||
@@ -52,9 +52,10 @@
|
||||
readonly (string name, Action<T> initialize, Func<T, bool> refresh)[] _property_monitors;
|
||||
|
||||
public PropertyChangeDetector() {
|
||||
_property_monitors = new (string name, Action<T> initialize, Func<T, bool> refresh)[ReflectionHelper.get_props<T>().Count];
|
||||
var num_props = ReflectionHelper.properties<T>().Count;
|
||||
_property_monitors = new (string, Action<T>, Func<T, bool>)[num_props];
|
||||
int i = 0;
|
||||
foreach (var pad in ReflectionHelper.prop_accessors<T>().Values) {
|
||||
foreach (var pad in ReflectionHelper.property_accessors<T>().Values) {
|
||||
var (initialize, refresh) = pad.create_snapshot();
|
||||
_property_monitors[i++] = (pad.prop_info.Name, initialize, refresh);
|
||||
}
|
||||
@@ -64,7 +65,7 @@
|
||||
_property_monitors = new (string name, Action<T> initialize, Func<T, bool> refresh)[props.Length];
|
||||
int ppos = 0, pm_pos = 0;
|
||||
while (ppos < props.Length) {
|
||||
if (ReflectionHelper.prop_accessors<T>().TryGetValue(props[ppos++], out var pad)) {
|
||||
if (ReflectionHelper.property_accessors<T>().TryGetValue(props[ppos++], out var pad)) {
|
||||
var (initialize, refresh) = pad.create_snapshot();
|
||||
_property_monitors[pm_pos++] = (pad.prop_info.Name, initialize, refresh);
|
||||
}
|
||||
|
||||
@@ -11,8 +11,9 @@
|
||||
static class DataGridFilterHelper {
|
||||
public static IDisposable hook_all<TSource, TRow>(TSource source, ICollectionView rows) =>
|
||||
hook_filters(rows,
|
||||
ReflectionHelper.property_delegates_of_type<TSource, IDataGridColumnFilter<TRow>>()
|
||||
.Select(f => f(source))
|
||||
ReflectionHelper.property_getters<TSource, IDataGridColumnFilter<TRow>>()
|
||||
.Cut2()
|
||||
.Curry(source)
|
||||
.ExceptNull()
|
||||
.ToList());
|
||||
|
||||
|
||||
@@ -48,6 +48,16 @@ namespace System.Collections.Generic {
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<T1> Cut1<T1, T2>(this IEnumerable<(T1, T2)> source) =>
|
||||
source.Select(tup => tup.Item1);
|
||||
|
||||
public static IEnumerable<T2> Cut2<T1, T2>(this IEnumerable<(T1, T2)> source) =>
|
||||
source.Select(tup => tup.Item2);
|
||||
|
||||
public static IEnumerable<TOut> Curry<TOut, TIn>(
|
||||
this IEnumerable<Func<TIn, TOut>> fns, TIn input) =>
|
||||
fns.Select(fn => fn(input));
|
||||
|
||||
public static IEnumerable<T> SelectWhereValues<T>(this IEnumerable<T?> source) where T : struct {
|
||||
foreach (var v in source) {
|
||||
if (v.HasValue) {
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
static class ReflectionHelper {
|
||||
/// <summary>
|
||||
/// Searches for a constructor with any set of parameters that are assignable by the types in
|
||||
/// <param name="ctr_type_args"/>
|
||||
/// <paramref name="ctr_type_args"/>
|
||||
/// </summary>
|
||||
/// <param name="target_type">The type of the constructor to be sought</param>
|
||||
/// <param name="ctr_type_args">The argument-types of the constructor to find</param>
|
||||
@@ -27,101 +27,13 @@
|
||||
/// The <see cref="ConstructorInfo"/> for <typeparamref name="T"/> with parameter types that
|
||||
/// match or are implicit in Type[] types argument
|
||||
/// </returns>
|
||||
public static ConstructorInfo FindApplicableConstructor(
|
||||
public static ConstructorInfo get_constructor(
|
||||
Type target_type, params Type[] ctr_type_args) {
|
||||
var constructors = target_type.GetConstructors();
|
||||
return _find_explicit_constructor(constructors, ctr_type_args) ??
|
||||
_find_implicit_constructor(constructors, ctr_type_args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an instance of a generic type
|
||||
/// </summary>
|
||||
/// <param name="generic_def">The generic type definition of object to create</param>
|
||||
/// <param name="generic_args">The generic type arguments of the object to create</param>
|
||||
/// <param name="ctr_args">The constructor arguments of the object to create</param>
|
||||
/// <returns>A reference to the newly created object</returns>
|
||||
///
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// The current type does not represent a generic type definition. That is,
|
||||
/// System.Type.IsGenericTypeDefinition returns false.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// typeArguments is null. -or- Any element of typeArguments is null.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="ArgumentException">
|
||||
/// The number of elements in typeArguments is not the same as the number of type parameters
|
||||
/// in the current generic type definition. -or- Any element of typeArguments does not satisfy
|
||||
/// the constraints specified for the corresponding type parameter of the current generic
|
||||
/// type. -or- typeArguments contains an element that is a pointer type (System.Type.IsPointer
|
||||
/// returns true), a by-ref type (System.Type.IsByRef returns true), or System.Void.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="ArgumentException">
|
||||
/// Does not find an applicable constructor for the provided arguments
|
||||
/// (<paramref name="ctr_args"/>)
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="ArgumentException"/>
|
||||
/// type is not a RuntimeType. -or- type is an open generic type (that is, the
|
||||
/// System.Type.ContainsGenericParameters property returns true).
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="NotSupportedException"/>
|
||||
/// type cannot be a System.Reflection.Emit.TypeBuilder. -or- Creation of System.TypedReference,
|
||||
/// System.ArgIterator, System.Void, and System.RuntimeArgumentHandle types, or arrays
|
||||
/// of those types, is not supported. -or- The assembly that contains type is a dynamic
|
||||
/// assembly that was created with System.Reflection.Emit.AssemblyBuilderAccess.Save.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="TargetInvocationException">
|
||||
/// The constructor being called throws an exception.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="MethodAccessException">
|
||||
/// The caller does not have permission to call this constructor.
|
||||
/// </exception>
|
||||
//
|
||||
/// <exception cref="MemberAccessException">
|
||||
/// Cannot create an instance of an abstract class, or this member was invoked with a
|
||||
/// late-binding mechanism.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="System.Runtime.InteropServices.InvalidComObjectException">
|
||||
/// The COM type was not obtained through Overload:System.Type.GetTypeFromProgID or
|
||||
/// Overload:System.Type.GetTypeFromCLSID.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="MissingMethodException">
|
||||
/// No matching public constructor was found.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="System.Runtime.InteropServices.COMException">
|
||||
/// type is a COM object but the class identifier used to obtain the type is invalid,
|
||||
/// or the identified class is not registered.
|
||||
/// </exception>
|
||||
///
|
||||
/// <exception cref="TypeLoadException">type is not a valid type.</exception>
|
||||
public static object CreateInstance(
|
||||
Type generic_def, Type[] generic_args, params object[] ctr_args) {
|
||||
if (!generic_def.IsGenericTypeDefinition) {
|
||||
throw Exceptions.not_generic_type_definition(generic_def);
|
||||
}
|
||||
|
||||
var t = generic_def.MakeGenericType(generic_args);
|
||||
if (ctr_args.Length == 0) {
|
||||
return Activator.CreateInstance(t);
|
||||
}
|
||||
|
||||
var constructor = FindApplicableConstructor(
|
||||
t, ctr_args.Select(c => c.GetType()).ToArray()) ??
|
||||
throw new ArgumentException(
|
||||
"Did not find applicable constructor for the provided arguments");
|
||||
return constructor.Invoke(ctr_args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the type arguments for a generic type, <paramref name="generic_def"/>, which is
|
||||
/// assignable from a particular instantiable type, <paramref name="type"/>
|
||||
@@ -141,7 +53,7 @@
|
||||
/// <paramref name="generic_def"/> does not represent a generic type
|
||||
/// definition (i.e., <see cref="Type.IsGenericTypeDefinition"/> is false)
|
||||
/// </exception>
|
||||
public static Type[] GetGenericTypeArgs(Type type, Type generic_def) {
|
||||
public static Type[] get_generic_type_args(Type type, Type generic_def) {
|
||||
if (!generic_def.IsGenericTypeDefinition) {
|
||||
throw Exceptions.not_generic_type_definition(generic_def);
|
||||
}
|
||||
@@ -152,11 +64,6 @@
|
||||
throw Exceptions.does_not_implement_or_derive_from(type, generic_def);
|
||||
}
|
||||
|
||||
public static Delegate create_property_getter(object obj, string property) =>
|
||||
create_property_getter(obj, obj.GetType().GetProperty(property) ??
|
||||
throw new ArgumentException(
|
||||
$"Failed to create getter for property '{property}'", nameof(property)));
|
||||
|
||||
public static Delegate create_property_getter(object obj, PropertyInfo prop_info) {
|
||||
if (obj is null) {
|
||||
throw new ArgumentNullException(nameof(obj));
|
||||
@@ -170,12 +77,12 @@
|
||||
nameof(prop_info));
|
||||
}
|
||||
|
||||
public static IReadOnlyList<PropertyInfo> get_props<T>(
|
||||
public static IReadOnlyList<PropertyInfo> properties<T>(
|
||||
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public,
|
||||
bool include_immutable = true) =>
|
||||
PropertyInfoStore<T>.get_props(flags, include_immutable);
|
||||
PropertyInfoStore<T>.get_properties(flags, include_immutable);
|
||||
|
||||
public static IReadOnlyDictionary<string, IPropertyAccessorData<T>> prop_accessors<T>() =>
|
||||
public static IReadOnlyDictionary<string, IPropertyAccessorData<T>> property_accessors<T>() =>
|
||||
DelegateStore<T>.accessor_data;
|
||||
|
||||
public static Func<T> create_property_getter<T>(object obj, string property) {
|
||||
@@ -200,11 +107,11 @@
|
||||
/// <summary>
|
||||
/// Gets 'getter' delegates for a set of properties
|
||||
/// </summary>
|
||||
public static IReadOnlyList<Func<TSource, TValue>> property_delegates_of_type<TSource, TValue>(
|
||||
public static IReadOnlyList<(string name, Func<TSource, TValue> get)> property_getters<TSource, TValue>(
|
||||
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public) =>
|
||||
PropertyGetterStore<TSource, TValue>.get_getters(flags);
|
||||
|
||||
public static IReadOnlyList<Func<TValue>> static_property_delegates_of_type<TValue>(
|
||||
public static IReadOnlyList<(string name, Func<TValue> get)> static_property_getters<TValue>(
|
||||
Type source_type) =>
|
||||
StaticPropertyGetterStore<TValue>.get(source_type);
|
||||
|
||||
@@ -303,7 +210,7 @@
|
||||
}
|
||||
|
||||
public static IDisposable create<T>(T instance) =>
|
||||
create(instance, PropertyInfoStore<T>.get_props(include_immutable: false));
|
||||
create(instance, PropertyInfoStore<T>.get_properties(include_immutable: false));
|
||||
|
||||
public static IDisposable create<T>(T instance, IReadOnlyList<PropertyInfo> props) {
|
||||
var snapshot = props.as_mutable().WrapSelectorRO(p => p.GetValue(instance)).ToList();
|
||||
@@ -417,7 +324,7 @@
|
||||
static class PropertyInfoStore<T> {
|
||||
static readonly AtomicDictionaryWrapper<BindingFlags, PropInfoSet> _props = new();
|
||||
|
||||
public static IReadOnlyList<PropertyInfo> get_props(
|
||||
public static IReadOnlyList<PropertyInfo> get_properties(
|
||||
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public,
|
||||
bool include_immutable = true
|
||||
) {
|
||||
@@ -465,7 +372,7 @@
|
||||
static DelegateStore() {
|
||||
var prop_dels = new Dictionary<string, IPropertyAccessorData<T>>();
|
||||
var accessor_type_cache = new Dictionary<Type, Type>();
|
||||
foreach (var p in PropertyInfoStore<T>.get_props()) {
|
||||
foreach (var p in PropertyInfoStore<T>.get_properties()) {
|
||||
prop_dels[p.Name] = (IPropertyAccessorData<T>)Activator.CreateInstance(
|
||||
accessor_type_cache.GetOrAdd(p.PropertyType, mk_prop_accessor_type),
|
||||
new[] { p });
|
||||
@@ -484,16 +391,16 @@
|
||||
}
|
||||
|
||||
static class PropertyGetterStore<TSource, TValue> {
|
||||
static readonly AtomicDictionaryWrapper<BindingFlags, IReadOnlyList<Func<TSource, TValue>>> _getters = new();
|
||||
static readonly AtomicDictionaryWrapper<BindingFlags, IReadOnlyList<(string, Func<TSource, TValue>)>> _getters = new();
|
||||
|
||||
public static readonly IReadOnlyList<Func<TSource, TValue>> value;
|
||||
|
||||
public static IReadOnlyList<Func<TSource, TValue>> get_getters(BindingFlags flags) {
|
||||
public static IReadOnlyList<(string, Func<TSource, TValue>)> get_getters(BindingFlags flags) {
|
||||
Log.assert(flags == (BindingFlags.Instance | BindingFlags.Public));
|
||||
return _getters.GetOrAdd(flags, _ => {
|
||||
var res = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(p => typeof(TValue).IsAssignableFrom(p.PropertyType))
|
||||
.Select(_prop_getter<TSource, TValue>)
|
||||
.Select(p => (p.Name, _prop_getter<TSource, TValue>(p)))
|
||||
.ToReadOnlyList();
|
||||
Log.assert(res.Count == value.Count);
|
||||
return res;
|
||||
@@ -510,9 +417,9 @@
|
||||
}
|
||||
|
||||
static class StaticPropertyGetterStore<TValue> {
|
||||
static Dictionary<Type, IReadOnlyList<Func<TValue>>> _cache = new();
|
||||
static Dictionary<Type, IReadOnlyList<(string, Func<TValue>)>> _cache = new();
|
||||
|
||||
public static IReadOnlyList<Func<TValue>> get(Type type) {
|
||||
public static IReadOnlyList<(string, Func<TValue>)> get(Type type) {
|
||||
// Updates to the cache are done atomically (thread-safe)
|
||||
var cache = _cache;
|
||||
if (cache.TryGetValue(type, out var getters)) {
|
||||
@@ -520,7 +427,7 @@
|
||||
}
|
||||
getters = type.GetProperties(BindingFlags.Public | BindingFlags.Static)
|
||||
.Where(p => typeof(TValue).IsAssignableFrom(p.PropertyType))
|
||||
.Select(p => (Func<TValue>)p.GetGetMethod().CreateDelegate(typeof(Func<TValue>)))
|
||||
.Select(p => (p.Name, (Func<TValue>)p.GetGetMethod().CreateDelegate(typeof(Func<TValue>))))
|
||||
.ToReadOnlyList();
|
||||
cache[type] = getters;
|
||||
_cache = cache;
|
||||
|
||||
Reference in new issue
Block a user