/// <summary> /// Gets the instance field or property identified by <paramref name="memberInfo"/> on /// the <paramref name="obj"/>. /// </summary> internal static object Get(this MemberInfo memberInfo, object obj) { MemberGetter getter = Reflect.Getter(memberInfo); object value = getter(obj); return(value); }
public PropertyAccess(Type t, string n, MemberGetter g, MemberSetter s) { Type = t; Name = n; Getter = g; Setter = s; }
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 }
static Getters() { testUri = new TestUri("SomeHost"); @class = testUri.GetType(); property = @class.GetProperty(propertyName, bindingFlags); fastProperty = new FastProperty(property, bindingFlags); getgetMethod = property.GetGetMethod(nonPublic: allowNonPublicFieldAccess); // Using FastMember - https://github.com/mgravell/fast-member fastMember = TypeAccessor.Create(@class, allowNonPublicAccessors: allowNonPublicFieldAccess); Type funcType = Type.GetType("System.Func`2[Benchmark.TestUri, System.String]"); getDelegate = (Func <TestUri, string>)Delegate.CreateDelegate(funcType, getgetMethod); getDelegateDynamic = Delegate.CreateDelegate(funcType, getgetMethod); Emit <Func <TestUri, string> > getterEmiter = Emit <Func <TestUri, string> > .NewDynamicMethod("GetTestUriProperty") .LoadArgument(0) .Call(getgetMethod) .Return(); funcTstring = getterEmiter.CreateDelegate(); ffgetter = Reflect.PropertyGetter(property); Emit <Func <object, object> > objGetterEmiterFunc = Emit <Func <object, object> > .NewDynamicMethod("GetMSTestUriProperty") .LoadArgument(0) .CastClass(typeof(TestUri)) .Call(getgetMethod) .Return(); funcObjObj = objGetterEmiterFunc.CreateDelegate(); }
public static void Init() { // Fetch rect acessors using Reflection Assembly UnityEngine = Assembly.GetAssembly(typeof(UnityEngine.GUI)); Type GUIClipType = UnityEngine.GetType("UnityEngine.GUIClip"); PropertyInfo topmostRect = GUIClipType.GetProperty("topmostRect", BindingFlags.Static | BindingFlags.Public); MethodInfo GetTopRect = GUIClipType.GetMethod("GetTopRect", BindingFlags.Static | BindingFlags.NonPublic); // Creating Fast.Reflection Delegates from those acessors // (First generic Parameter) -> Not actually GUI we're calling on but we cannot adress GUIClip as it's private and it's static so we would pass null anyways: GetTopRectDelegate = GetTopRect.DelegateForCall <GUI, Rect> (); topmostRectDelegate = topmostRect.DelegateForGet <GUI, Rect> (); // As we can call Begin/Ends inside another, we need to save their states hierarchial in Lists (not Stack, as we need to iterate over them!): currentRectStack = new List <Rect> (); rectStackGroups = new List <List <Rect> > (); GUIMatrices = new List <Matrix4x4> (); adjustedGUILayout = new List <bool> (); // Sometimes, strange errors pop up (related to Mac?), which we try to catch and enable a compability Mode no supporting zooming in groups try { topmostRectDelegate.Invoke(null); } catch { Debug.LogWarning("GUIScaleUtility cannot run on this system! Compability mode enabled. For you that means you're not able to use the Node Editor inside more than one group:( Please PM me (Seneral @UnityForums) so I can figure out what causes this! Thanks!"); compabilityMode = true; } initiated = true; }
public static MemberGetter <TTarget, TReturn> DelegateForGet <TTarget, TReturn>(this FieldInfo field) { int key = GetKey <TTarget, TReturn>(field.GetHashCode(), kFieldGetterName); Delegate result; if (cache.TryGetValue(key, out result)) { return((MemberGetter <TTarget, TReturn>)result); } #if HAS_EMIT return(GenDelegateForMember <MemberGetter <TTarget, TReturn>, FieldInfo>( field, key, kFieldGetterName, GenFieldGetter <TTarget>, typeof(TReturn), typeof(TTarget))); #else MemberGetter <TTarget, TReturn> methodDelegate = (TTarget target) => { var value = field.GetValue(target); return(value is TReturn ? (TReturn)value : default(TReturn)); }; cache[key] = methodDelegate; return(methodDelegate); #endif }
private MemberGetter TryCacheGet(Type targetType, string propertyName) { var key = new CacheKey(targetType, propertyName); MemberGetter getter; if (IsCacheable(targetType)) { //there should only be few writers to this bit at execution time // note that this could be locked inside the MemberGetter delegate (below) // todo: cache all these during initialization locker.EnterWriteLock(); if (getters.TryGetValue(key, out getter) == false) { getters[key] = getter = targetType.DelegateForGetPropertyValue(propertyName, Flags.InstanceAnyVisibility); } locker.ExitWriteLock(); return(getter); } if (getters.TryGetValue(key, out getter) == false) { getters[key] = getter = new MemberGetter(impl => { var implementationGetter = TryCacheGet(impl.GetType(), propertyName); return(implementationGetter(impl)); }); } return(getter); }
public static MemberGetter <TTarget, TReturn> DelegateForGet <TTarget, TReturn>(this PropertyInfo property) { if (!property.CanRead) { throw new InvalidOperationException("Property is not readable " + property.Name); } int key = GetKey <TTarget, TReturn>(property.GetHashCode(), kPropertyGetterName); Delegate result; if (cache.TryGetValue(key, out result)) { return((MemberGetter <TTarget, TReturn>)result); } #if HAS_EMIT return(GenDelegateForMember <MemberGetter <TTarget, TReturn>, PropertyInfo>( property, key, kPropertyGetterName, GenPropertyGetter <TTarget>, typeof(TReturn), typeof(TTarget))); #else MemberGetter <TTarget, TReturn> methodDelegate = (TTarget target) => { var value = property.GetValue(target, null); return(value is TReturn ? (TReturn)value : default(TReturn)); }; cache[key] = methodDelegate; return(methodDelegate); #endif }
public void SetValue(object instance, object value) { if (SetValueFn == null) { return; } if (!Type.IsInstanceOfType(value)) { lock (this) { //Only caches object converter used on first use if (ConvertType == null) { ConvertType = value.GetType(); ConvertValueFn = TypeConverter.CreateTypeConverter(ConvertType, Type); } } if (ConvertType.IsInstanceOfType(value)) { value = ConvertValueFn(value); } else { var tempConvertFn = TypeConverter.CreateTypeConverter(value.GetType(), Type); value = tempConvertFn(value); } } SetValueFn(instance, value); }
private void Map(MemberGetter fromMember, MemberSetter toMember) { if (fromMember != null && toMember != null) { this.memberMaps.Add(new MemberMap(fromMember, toMember)); } }
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)); }
/// <summary> /// Initializes a new instance of the <see cref="TableEqualityComparer{T}"/> class. /// </summary> /// <param name="typeInfo">The information about the table.</param> public TableEqualityComparer(SqlTypeInfo typeInfo) { InitialHash = typeInfo.FullyQualifiedTableName.GetHashCode() * -1977; StringComparer = typeInfo.Adapter.StringComparer; List <MemberGetter> stringGetters = new List <MemberGetter>(); List <MemberGetter> otherGetters = new List <MemberGetter>(); List <MemberGetter> byteGetters = new List <MemberGetter>(); foreach (SqlColumn column in typeInfo.EqualityColumns) { MemberGetter getter = column.Getter; if (column.Type == typeof(byte[])) { byteGetters.Add(getter); } else if (column.Type == typeof(string) && StringComparer != System.StringComparer.Ordinal) { stringGetters.Add(getter); } else { otherGetters.Add(getter); } } StringGetters = stringGetters.Count == 0 ? Array.Empty <MemberGetter>() : stringGetters.ToArray(); Getters = otherGetters.Count == 0 ? Array.Empty <MemberGetter>() : otherGetters.ToArray(); ByteArrayGetters = byteGetters.Count == 0 ? Array.Empty <MemberGetter>() : byteGetters.ToArray(); }
public static void Init () { // Fetch rect acessors using Reflection Assembly UnityEngine = Assembly.GetAssembly (typeof (UnityEngine.GUI)); Type GUIClipType = UnityEngine.GetType ("UnityEngine.GUIClip"); PropertyInfo topmostRect = GUIClipType.GetProperty ("topmostRect", BindingFlags.Static | BindingFlags.Public); MethodInfo GetTopRect = GUIClipType.GetMethod ("GetTopRect", BindingFlags.Static | BindingFlags.NonPublic); // Creating Fast.Reflection Delegates from those acessors // (First generic Parameter) -> Not actually GUI we're calling on but we cannot adress GUIClip as it's private and it's static so we would pass null anyways: GetTopRectDelegate = GetTopRect.DelegateForCall<GUI, Rect> (); topmostRectDelegate = topmostRect.DelegateForGet<GUI, Rect> (); // As we can call Begin/Ends inside another, we need to save their states hierarchial in Lists (not Stack, as we need to iterate over them!): currentRectStack = new List<Rect> (); rectStackGroups = new List<List<Rect>> (); GUIMatrices = new List<Matrix4x4> (); adjustedGUILayout = new List<bool> (); // Sometimes, strange errors pop up (related to Mac?), which we try to catch and enable a compability Mode no supporting zooming in groups try { topmostRectDelegate.Invoke (null); } catch { Debug.LogWarning ("GUIScaleUtility cannot run on this system! Compability mode enabled. For you that means you're not able to use the Node Editor inside more than one group:( Please PM me (Seneral @UnityForums) so I can figure out what causes this! Thanks!"); compabilityMode = true; } initiated = true; }
public void Can_Get_Field_Getter() { var fieldInfo = typeof(TestObject).GetField("SomeField"); MemberGetter <object, object> getter = null; Assert.DoesNotThrow(() => { getter = fieldInfo.DelegateForGet(); }); Assert.IsNotNull(getter); }
public void Can_Get_Property_Getter() { var propertyInfo = typeof(TestObject).GetProperty("SomeProperty"); MemberGetter <object, object> getter = null; Assert.DoesNotThrow(() => { getter = propertyInfo.DelegateForGet(); }); Assert.IsNotNull(getter); }
private object GetNameTableFromState(object state) { if (getterForNameTable == null) { getterForNameTable = state.GetType().DelegateForGetFieldValue("NameTable"); } return(getterForNameTable(state)); }
public void Ctor_ConstructorInfo_ShouldBeMethodTypeUndefined() { var constructor = typeof(NameValueCollection).GetConstructor(Type.EmptyTypes); var member = new MemberGetter(constructor); Assert.AreEqual(MemberType.Undefined, member.MemberType); }
/// <summary> /// Executes the delegate on the specified target only if it's not null, returns default(TReturn) otherwise /// </summary> public static TReturn SafeInvoke <TTarget, TReturn>(this MemberGetter <TTarget, TReturn> getter, TTarget target) { if (getter != null) { return(getter(target)); } return(default(TReturn)); }
public MemberGetter GetGetter(Type type, String Name) { if (type != null && !String.IsNullOrEmpty(Name)) { if (this.unsensitive) { Name = Name.ToUpper(); } Dictionary <String, MemberGetter> innerDict = null; if (!_cacheGetter.ContainsKey(type)) { lock (lck) { if (!_cacheGetter.ContainsKey(type)) { _cacheGetter[type] = innerDict = new Dictionary <String, MemberGetter>(); } } } innerDict = _cacheGetter[type]; if (!innerDict.ContainsKey(Name)) { lock (lck) { if (!innerDict.ContainsKey(Name)) { MemberGetter getter = 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) { getter = type.DelegateForGetPropertyValue(property.Name); } if (getter == null) { if (field != null) { getter = type.DelegateForGetFieldValue(field.Name); } } } innerDict[Name] = getter; } } } return(innerDict.ContainsKey(Name) ? innerDict[Name] : null); } return(null); }
public PropertyAccessor( PropertyInfo propertyInfo, MemberGetter publicGetter, MemberSetter publicSetter) { PropertyInfo = propertyInfo; PublicGetter = publicGetter; PublicSetter = publicSetter; }
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); }
private MemberGetter GetMemberGetter(Type type) { if (type != _memberGetterType) { _memberGetter = FasterflectManager.GetFieldGetter(type, info.Value.Name); _memberGetterType = type; } return(_memberGetter); }
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 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; }
public static void ExtractDependencyIdentifier(BinaryWriter binaryWriter, object obj) { var dataTable = obj as DataTable; if (_objectIDGetter == null) { _objectIDGetter = dataTable.GetType().DelegateForGetFieldValue("_objectID"); } binaryWriter.Write(Convert.ToString(_objectIDGetter(dataTable))); }
public ReflectionGetterBenchmark() { _indexerEntity = new("hello word.", 1, 0.99M); var property = typeof(IndexerEntity).GetTypeInfo().GetProperty("Prop1"); _property = typeof(IndexerEntity).GetTypeInfo().GetProperty("Prop1"); _reflector = property.GetReflector(); _dotNextGetter = Type <IndexerEntity> .Property <string> .RequireGetter(nameof(IndexerEntity.Prop1)); DynamicInvoker a; }
public FieldAccessor( FieldInfo fieldInfo, MemberGetter publicGetter, MemberSetter publicSetter, MemberRefSetter publicSetterRef) { FieldInfo = fieldInfo; PublicGetter = publicGetter; PublicSetter = publicSetter; PublicSetterRef = publicSetterRef; }
internal MemberGetter GetReader(string memberName) { int index = Array.IndexOf(paramNames, memberName); MemberGetter reader = paramValueReaders[index]; if (reader == null) { reader = paramKinds[index] ? type.DelegateForGetFieldValue(memberName) : type.DelegateForGetPropertyValue(memberName); paramValueReaders[index] = reader; } return reader; }
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 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; }
/// <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 static Func<Object, Object> MakeValueGetter(String fieldName, MemberGetter getter) { return (entity) => { try { return getter(entity); } catch (Exception ex) { throw new UnableToGetTheFieldValueException(ex, fieldName); } }; }
public override void RuntimeInitialize(LocationInfo locationInfo) { _eventGetter = locationInfo.DeclaringType.DelegateForGetFieldValue(EventName); base.RuntimeInitialize(locationInfo); }
// private static Type GUILayoutGroupType; // private static Type GUILayoutEntryType; // // private static FieldInfo LayoutGroupRect; // private static FieldInfo LayoutEntryHeight; // private static FieldInfo LayoutEntryWidth; // private static PropertyInfo LayoutEntryStyle; public static void Init() { Assembly UnityEngine = Assembly.GetAssembly (typeof (UnityEngine.GUI)); Type GUIClipType = UnityEngine.GetType ("UnityEngine.GUIClip"); PropertyInfo topmostRect = GUIClipType.GetProperty ("topmostRect", BindingFlags.Static | BindingFlags.Public); MethodInfo GetTopRect = GUIClipType.GetMethod ("GetTopRect", BindingFlags.Static | BindingFlags.NonPublic); // Not actually GUI we're calling on but we cannot adress GUIClip as it's private and it's static so we would pass null anyways: GetTopRectDelegate = GetTopRect.DelegateForCall<GUI, Rect> (); topmostRectDelegate = topmostRect.DelegateForGet<GUI, Rect> (); // As we can call Begin/Ends inside another, we need to save their states hierarchial in Lists: currentRectStack = new List<Rect> (); rectStackGroups = new List<List<Rect>> (); GUIMatrices = new List<Matrix4x4> (); adjustedGUILayout = new List<bool> (); try { topmostRectDelegate.Invoke (null); } catch { Debug.LogWarning ("GUIScaleUtility cannot run on this system! Compability mode enabled. For you that means you're not able to use the Node Editor inside more than one group:( Please PM me (Seneral @UnityForums) so I can figure out what causes this! Thanks!"); compabilityMode = true; } // Type GUILayoutUtilityType = UnityEngine.GetType ("UnityEngine.GUILayoutUtility"); // currentGUILayoutCache = GUILayoutUtilityType.GetField ("current", BindingFlags.Static | BindingFlags.NonPublic); // // Type GUILayoutCacheType = GUILayoutUtilityType.GetNestedType ("LayoutCache", BindingFlags.NonPublic); // currentTopLevelGroup = GUILayoutCacheType.GetField ("topLevel", BindingFlags.NonPublic | BindingFlags.Instance); // // GUILayoutGroupType = UnityEngine.GetType ("UnityEngine.GUILayoutGroup"); // GUILayoutEntryType = UnityEngine.GetType ("UnityEngine.GUILayoutEntry"); // // LayoutGroupRect = GUILayoutGroupType.GetField ("rect"); // // LayoutEntryHeight = GUILayoutEntryType.GetField ("maxHeight"); // LayoutEntryWidth = GUILayoutEntryType.GetField ("maxWidth"); // LayoutEntryStyle = GUILayoutEntryType.GetProperty ("style"); }
private MemberGetter TryCacheGet(Type targetType, string propertyName) { var key = new CacheKey(targetType, propertyName); MemberGetter getter; if(IsCacheable(targetType)) { //there should only be few writers to this bit at execution time // note that this could be locked inside the MemberGetter delegate (below) // todo: cache all these during initialization locker.EnterWriteLock(); if (getters.TryGetValue(key, out getter) == false) { getters[key] = getter = targetType.DelegateForGetPropertyValue(propertyName, Flags.InstanceAnyVisibility); } locker.ExitWriteLock(); return getter; } if(getters.TryGetValue(key,out getter)==false) { getters[key] = getter = new MemberGetter(impl => { var implementationGetter = TryCacheGet(impl.GetType(), propertyName); return implementationGetter(impl); }); } return getter; }