Пример #1
0
        private static Action <object, T> FieldOrPropertySetter <T>(Type type, string fieldName)
        {
            Action <object, T> Searcher(Type innerType)
            {
                Expression <Action <object, T> > setter;
                var fieldInfo = innerType.GetField(fieldName, AccessTools.all);

                if (fieldInfo != null)
                {
                    setter = (obj, val) => fieldInfo.SetValue(obj, val);
                    return(setter.Compile());
                }

                var propertyInfo = innerType.GetProperty(fieldName, AccessTools.all);

                if (propertyInfo != null)
                {
                    setter = (obj, val) => propertyInfo.SetValue(obj, val, NoArgs);
                    return(setter.Compile());
                }

                return(null);
            }

            var result = AccessTools.FindIncludingBaseTypes(type, Searcher);

            if (result != null)
            {
                return(result);
            }

            throw new ArgumentException(
                      $"Unable to find a field or property setter named {fieldName} on {type.GetPrettyTypeName()}");
        }
Пример #2
0
        private static Func <object, T> FieldOrPropertyGetter <T>(Type type, string fieldName)
        {
            Func <object, T> Searcher(Type innerType)
            {
                Expression <Func <object, T> > getter = null;

                var fieldInfo = innerType.GetField(fieldName, AccessTools.all);

                if (fieldInfo != null)
                {
                    getter = obj => (T)fieldInfo.GetValue(obj);
                    return(getter.Compile());
                }

                var propertyInfo = innerType.GetProperty(fieldName, AccessTools.all);

                if (propertyInfo != null)
                {
                    getter = obj => (T)propertyInfo.GetValue(obj, NoArgs);
                    return(getter.Compile());
                }

                return(null);
            }

            var result = AccessTools.FindIncludingBaseTypes(type, Searcher);

            if (result != null)
            {
                return(result);
            }

            throw new ArgumentException(
                      $"Unable to find a field or property getter named {fieldName} on {type.GetPrettyTypeName()}");
        }