public void Setup([NotNull] FieldInfo setFieldInfo) { fieldInfo = setFieldInfo; #if ((UNITY_EDITOR || UNITY_STANDALONE) && !NET_STANDARD_2_0) && USE_IL_FOR_GET_AND_SET // Handle const values. if (setFieldInfo.IsLiteral && setFieldInfo.IsStatic) { var fieldType = setFieldInfo.FieldType; // FastReflection only supports following types when it comes to constants if (fieldType != Types.Bool && fieldType != Types.Int && fieldType != Types.Float && fieldType != Types.Double) { return; } } getValue = setFieldInfo.DelegateForGet(); #if UNITY_2018_1_OR_NEWER if (setFieldInfo.IsDefined(typeof(Unity.Collections.ReadOnlyAttribute), false)) { return; } #endif if (!setFieldInfo.IsInitOnly && !setFieldInfo.IsLiteral && !setFieldInfo.IsDefined(typeof(System.ComponentModel.ImmutableObjectAttribute), false) && !setFieldInfo.FieldType.IsDefined(typeof(System.ComponentModel.ReadOnlyAttribute), true)) { setValue = setFieldInfo.DelegateForSet(); #if DEV_MODE && DEBUG_CAN_WRITE Debug.Log(StringUtils.ToColorizedString(setFieldInfo.Name, ".CanWrite=", true, " with IsInitOnly=", setFieldInfo.IsInitOnly)); #endif } #endif }
private void Map(MemberGetter fromMember, MemberSetter toMember) { if (fromMember != null && toMember != null) { this.memberMaps.Add(new MemberMap(fromMember, toMember)); } }
public PropertyAccess(Type t, string n, MemberGetter g, MemberSetter s) { Type = t; Name = n; Getter = g; Setter = s; }
/// <summary> /// Executes the delegate on the specified target and value but only if it's not null /// </summary> public static void SafeInvoke <TTarget, TValue>(this MemberSetter <TTarget, TValue> setter, ref TTarget target, TValue value) { if (setter != null) { setter(ref target, value); } }
public void SetWithArg_stringToMemberOfType_expected <T>(string toSet, T expected) { FieldSample <T> sample = new FieldSample <T>(); MemberAttribute fieldAttr = new MemberAttribute(new NArgAttribute(), GetSingleMemberInfo(sample, "_field")); MemberSetter.SetArg(sample, fieldAttr, toSet); MemberAttribute propAttr = new MemberAttribute(new NArgAttribute(), GetSingleMemberInfo(sample, "TestProp")); MemberSetter.SetArg(sample, propAttr, toSet); MemberAttribute methodAttr = new MemberAttribute(new NArgAttribute(), GetSingleMemberInfo(sample, "TestMethod")); MemberSetter.SetArg(sample, methodAttr, toSet); MemberAttribute methodWithNoArgsAttr = new MemberAttribute(new NArgAttribute(), GetSingleMemberInfo(sample, "TestMethodWithNoArgs")); MemberSetter.SetArg(sample, methodWithNoArgsAttr, toSet); Assert.That(sample.FieldProp, Is.EqualTo(expected)); Assert.That(sample.TestProp, Is.EqualTo(expected)); Assert.That(sample.TestMethodProp, Is.EqualTo(expected)); Assert.That(sample.HasTestMethodWithNoArgsExecuted, Is.True); }
static InternalAccessor() { var type = typeof(List <T>); ArrayGetter = FastReflection.DelegateForGet <List <T>, T[]>(type.GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance)); CountSetter = FastReflection.DelegateForSet <List <T>, int>(type.GetField("_size", BindingFlags.NonPublic | BindingFlags.Instance)); }
public static MemberSetter <TTarget, TValue> DelegateForSet <TTarget, TValue>(this PropertyInfo property) { if (!property.CanWrite) { throw new InvalidOperationException("Property is not writable " + property.Name); } int key = GetKey <TTarget, TValue>(property.GetHashCode(), kPropertySetterName); Delegate result; if (cache.TryGetValue(key, out result)) { return((MemberSetter <TTarget, TValue>)result); } #if HAS_EMIT return(GenDelegateForMember <MemberSetter <TTarget, TValue>, PropertyInfo>( property, key, kPropertySetterName, GenPropertySetter <TTarget>, typeof(void), typeof(TTarget).MakeByRefType(), typeof(TValue))); #else MemberSetter <TTarget, TValue> methodDelegate = (ref TTarget target, TValue value) => { MethodInfo setMethod = property.GetSetMethod(/*nonPublic:*/ true); if (setMethod != null) { setMethod.Invoke(target, new object[] { value }); } }; cache[key] = methodDelegate; return(methodDelegate); #endif }
public void Can_Get_Field_Setter() { var fieldInfo = typeof(TestObject).GetField("SomeField"); MemberSetter <object, object> setter = null; Assert.DoesNotThrow(() => { setter = fieldInfo.DelegateForSet(); }); Assert.IsNotNull(setter); }
public void Can_Get_Property_Setter() { var propertyInfo = typeof(TestObject).GetProperty("SomeProperty"); MemberSetter <object, object> setter = null; Assert.DoesNotThrow(() => { setter = propertyInfo.DelegateForSet(); }); Assert.IsNotNull(setter); }
public ReflectionSetterBenchmark() { _indexerEntity = new("hello word.", 1, 0.99M); var property = typeof(IndexerEntity).GetTypeInfo().GetProperty("Prop1"); _reflector = property.GetReflector(); _dotNextSetter = Type <IndexerEntity> .Property <string> .RequireSetter(nameof(IndexerEntity.Prop1)); }
public MemberSetter GetSetter(Type type, String Name) { if (type != null && !String.IsNullOrEmpty(Name)) { if (this.unsensitive) { Name = Name.ToUpper(); } Dictionary <String, MemberSetter> innerDict = null; if (!_cacheSetter.ContainsKey(type)) { lock (lck) { if (!_cacheSetter.ContainsKey(type)) { _cacheSetter[type] = innerDict = new Dictionary <String, MemberSetter>(); } } } innerDict = _cacheSetter[type]; if (!innerDict.ContainsKey(Name)) { lock (lck) { if (!innerDict.ContainsKey(Name)) { MemberSetter setter = null; PropertyInfo property = this.unsensitive ? type.GetProperties().FirstOrDefault(p => p.Name.ToUpper().Equals(Name)) : type.GetProperty(Name); FieldInfo field = this.unsensitive ? type.GetFields().FirstOrDefault(p => p.Name.ToUpper().Equals(Name)) : type.GetField(Name); if (property != null || field != null) { if (property != null) { setter = type.DelegateForSetPropertyValue(property.Name); } if (setter == null) { if (field != null) { setter = type.DelegateForSetFieldValue(field.Name); } } } innerDict[Name] = setter; } } } return(innerDict.ContainsKey(Name) ? innerDict[Name] : null); } return(null); }
public PropertyAccessor( PropertyInfo propertyInfo, MemberGetter publicGetter, MemberSetter publicSetter) { PropertyInfo = propertyInfo; PublicGetter = publicGetter; PublicSetter = publicSetter; }
private MemberSetter GetMemberSetter(Type type) { if (type != _memberSetterType) { _memberSetter = FasterflectManager.GetFieldSetter(type, info.Value.Name); _memberSetterType = type; } return(_memberSetter); }
public void SetRemainingArg_EmptyStringArrayToIEnumerableOfSring_DoesNotThrow() { var sample = new FieldSample <int>(); string[] empty = new string[] { }; MemberAttribute propAttr = new MemberAttribute(new NArgAttribute(), GetSingleMemberInfo(sample, "FooProp")); MemberSetter.SetRemainingArg(sample, propAttr, empty); }
public AssignmentEntry(string name, AssignmentMember @from, AssignmentMember to) { Name = name; From = @from; To = to; GetValueFn = From.CreateGetter(); SetValueFn = To.CreateSetter(); ConvertValueFn = TypeConverter.CreateTypeConverter(From.Type, To.Type); }
public StrongReflectiveSerializer(string member0, StrongWriter <TMember0> writer0, StrongReader <TMember0> reader0) { var flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; var member = typeof(TTarget).GetMemberFromAll(member0, flags); _setter0 = DelegateForSet <TTarget, TMember0>(member); _getter0 = DelegateForGet <TTarget, TMember0>(member); _writer0 = writer0; _reader0 = reader0; }
private Field(FieldInfo field) : base(field) { //TODO: Should be optimized when LINQ Expression will have a support for ref return provider = Lambda <Provider>(Call(typeof(Unsafe), nameof(Unsafe.AsRef), new[] { field.FieldType }, Field(null, field))).Compile(); const BindingFlags staticPrivate = BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.NonPublic; getter = GetType().GetMethod(nameof(GetValue), staticPrivate).CreateDelegate <MemberGetter <V> >(provider); setter = field.IsInitOnly ? null : GetType().GetMethod(nameof(SetValue), staticPrivate).CreateDelegate <MemberSetter <V> >(provider); }
public LightSerializationMember(SerializationMemberInfo memberInfo) { this.Getter = memberInfo.Getter; this.Setter = memberInfo.Setter; this.Serializer = memberInfo.Serializer; this.MemberInfo = memberInfo.MemberInfo; this.SerializedName = memberInfo.GetSerializedName(); this.SerializeAsCData = memberInfo.SerializeAsCData; this.XmlTreatAsNullIfEmpty = memberInfo.HasApplicableAttribute(typeof(XmlTreatAsNullIfEmptyAttribute)); this.LogicalType = memberInfo.LogicalType; }
public FieldAccessor( FieldInfo fieldInfo, MemberGetter publicGetter, MemberSetter publicSetter, MemberRefSetter publicSetterRef) { FieldInfo = fieldInfo; PublicGetter = publicGetter; PublicSetter = publicSetter; PublicSetterRef = publicSetterRef; }
public static void Main() { ConstructorInvoker ctor = Reflect.Constructor(typeof(long)); MemberGetter getValue = Reflect.Getter(typeof(long), "m_value"); MemberSetter setValue = Reflect.Setter(typeof(long), "m_value"); long integer = (long)ctor(); ValueTypeHolder holder = new ValueTypeHolder(integer); // IMPORTANT! setValue(holder, 8L); Console.WriteLine(getValue(holder)); Console.ReadLine(); }
public FastValueRegisterExecuter(object owner, string propertyName, Action <T> loadAction, Func <T> getPropertyOfTheObjectFunction) { PropertyName = propertyName; _owner = owner; var type = owner.GetType(); _propertyGetter = type.DelegateForGetPropertyValue(propertyName); _propertySetter = type.DelegateForSetPropertyValue(propertyName); _loadAction = loadAction; _getPropertyOfTheObjectFunction = getPropertyOfTheObjectFunction; }
protected override void Initialize() { string call = attribute.Call; string set = attribute.Set; if (!set.IsNullOrEmpty()) { try { var field = targetType.GetField(set, Flags.InstanceAnyVisibility); _setter = field.DelegateForSet(); } catch { try { var property = targetType.GetProperty(set, Flags.InstanceAnyVisibility); _setter = property.DelegateForSet(); } catch { throw new vMemberNotFound(targetType, set); } } } if (!call.IsNullOrEmpty()) { try { var methods = targetType.GetAllMembers(typeof(object)).OfType <MethodInfo>(); _onChanged = (from method in methods where method.Name == call where method.ReturnType == typeof(void) let args = method.GetParameters() where args.Length == 1 where args[0].ParameterType.IsAssignableFrom(memberType) select method).FirstOrDefault().DelegateForCall(); } catch { throw new vMemberNotFound(targetType, call); } } _previousValue = memberValue; if (member.CollectionCount != -1) { _previousCollectionCount = member.CollectionCount; } }
private void WriteCollectionSizeToField(TContainingType obj) { //We must first access the collection to get the size and then write it into the field //before we try to truly serialize it ICollection enumerable = CollectionGetter.Getter(obj) as ICollection; if (enumerable == null) { throw new InvalidOperationException($"Tried to read the size of collection in Type: {typeof(TContainingType).Name} but did not implement {nameof(ICollection)}."); } MemberSetter.Setter(obj, GenericMath.Convert <int, TSizeType>(enumerable.Count)); }
/// <inheritdoc /> public override async Task SetMemberAsync(TContainingType obj, IWireStreamReaderStrategyAsync source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } #if NET35 throw new NotImplementedException(); #else MemberSetter.Setter(obj, (TMemberType)await TypeSerializer.ReadAsync(source).ConfigureAwait(false)); #endif }
/// <inheritdoc/> public override void Dispose() { #if ((UNITY_EDITOR || UNITY_STANDALONE) && !NET_STANDARD_2_0) && USE_IL_FOR_GET_AND_SET getValue = null; setValue = null; #endif #if UNITY_EDITOR serializedProperty = null; #endif LinkedMemberInfoPool.Dispose(this); }
private Field(FieldInfo field) : base(field) { if (field.DeclaringType is null) { throw new ArgumentException(ExceptionMessages.ModuleMemberDetected(field), nameof(field)); } var instanceParam = Parameter(field.DeclaringType.MakeByRefType()); var valueParam = Parameter(field.FieldType); getter = Lambda <MemberGetter <T, V> >(Field(instanceParam, field), instanceParam).Compile(); setter = field.IsInitOnly ? null : Lambda <MemberSetter <T, V> >(Assign(Field(instanceParam, field), valueParam), instanceParam, valueParam).Compile(); }
/// <summary> /// Creates single key queries. /// </summary> /// <typeparam name="KeyType">The key type.</typeparam> /// <param name="threadSafety">Determines the thread safe access for the</param> internal void Create<KeyType>(LazyThreadSafetyMode threadSafety) { SqlQueries<T> queries = (SqlQueries<T>) Queries; MemberSetter setter = EqualityColumns[0].Setter; ObjectFromKey = (key) => { object result = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(T)); setter(result, key); return (T) result; }; queries.LazyBulkDeleteKeys = new Lazy<DbKeysInt<T>>(() => CreateBulkDeleteKeys<KeyType>(), threadSafety); queries.LazyBulkGetKeys = new Lazy<DbKeysList<T>>(() => CreateBulkGetKeys<KeyType>(), threadSafety); queries.LazyGetKeysKeys = new Lazy<DbWhereKeys>(() => CreateGetKeysKeys<KeyType>(), threadSafety); queries.GetKey = CreateGetKey(); queries.DeleteKey = CreateDeleteKey(); }
public override void SetMember(TContainingType obj, [NotNull] IWireStreamReaderStrategy source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } try { MemberSetter.Setter(obj, (TMemberType)TypeSerializer.Read(source)); } catch (Exception e) { throw new InvalidOperationException($"Failed to set member {MemberInformation.Name} on Type: {MemberInformation.DeclaringType} for Type: {obj.GetType().Name} Exception: {e.Message}.", e); } }
public void SetValue(AssignableValue assignableValue, object destination) { Logger.Create(this).Debug("Setting value on '{0}' using assignable value:{1}{2}", destination, Environment.NewLine, assignableValue); MemberSetter setter = TryCacheSet(destination.GetType(), assignableValue.PropertyName); try { setter(destination, assignableValue.DestinationValue); } catch (Exception ex) { throw new DittoExecutionException(ex, "Failure while mapping '{0}'{1}{2}", assignableValue, Environment.NewLine, ex); } }
protected override void OnSingleInitialization() { string call = attribute.Call; string set = attribute.Set; if (!set.IsNullOrEmpty()) { try { var field = targetType.GetField(set, Flags.InstanceAnyVisibility); setter = field.DelegateForSet(); } catch { try { var property = targetType.GetProperty(set, Flags.InstanceAnyVisibility); setter = property.DelegateForSet(); } catch { throw new MemberNotFoundException("Failed to get a field or property to set with the name: " + set); } } } if (!call.IsNullOrEmpty()) { try { var methods = targetType.GetAllMembers(typeof(object)).OfType <MethodInfo>(); onChanged = (from method in methods where method.Name == call where method.ReturnType == typeof(void) let args = method.GetParameters() where args.Length == 1 where args[0].ParameterType.IsAssignableFrom(memberType) select method).FirstOrDefault().DelegateForCall(); } catch { throw new MemberNotFoundException(string.Format("Couldn't find an appropriate method to call with the name: {0} on target {1} when apply OnChanged on member {2}", call, rawTarget, member.Name)); } } previous = memberValue; }
/// <summary> /// Initializes a new instance of the <see cref="Field"/> class. /// </summary> /// <param name="prop">The prop.</param> /// <param name="entityType"></param> public Field(PropertyInfo prop, Type entityType) { _Prop = prop; setter = prop.DelegateForSetPropertyValue(); getter = prop.DelegateForGetPropertyValue(); }
private void PrecacheReflections(Type controllerType) { var defaultConstructor = controllerType.GetConstructors().FirstOrDefault(x => x.GetParameters().Length == 0); if (defaultConstructor == null) throw new ArgumentException("StatementHandler " + controllerType.Name + " does not have a default constructor"); activator = FastFlect.GetActivator(defaultConstructor); delegateForScopeSetter = controllerType.DelegateForSetPropertyValue("Scope"); delegateForContextSetter = controllerType.DelegateForSetPropertyValue("Context"); delegateForAttachmentsSetter = controllerType.DelegateForSetPropertyValue("Attachments"); delegateForTracerSetter = controllerType.DelegateForSetPropertyValue("Tracer"); delegateForInvokation = definition.MethodInfo.DelegateForCallMethod(); if (definition.TransformsScopeTo != null) { scopeConverter = StaticAnalysis.CreateConverter(definition.TransformsScopeTo); transformsToValueType = definition.TransformsScopeTo.IsValueType; } }
public LightSerializationMember(SerializationMemberInfo memberInfo) { this.Getter = memberInfo.Getter; this.Setter = memberInfo.Setter; this.Serializer = memberInfo.Serializer; this.MemberInfo = memberInfo.MemberInfo; this.SerializedName = memberInfo.GetSerializedName(); this.SerializeAsCData = memberInfo.SerializeAsCData; this.XmlTreatAsNullIfEmpty = memberInfo.HasApplicableAttribute(typeof(XmlTreatAsNullIfEmptyAttribute)); this.LogicalType = memberInfo.LogicalType; }
private static Action<Object, Object> MakeValueSetter(String fieldName, MemberSetter setter) { return (entity, value) => { try { setter(entity, value); } catch (Exception ex) { throw new UnableToSetTheFieldValueException(ex, fieldName, value); } }; }