Exemplo n.º 1
0
        /// <summary>
        /// 将di属性写入对象(第2次调用后性能 约等于手写)
        /// </summary>
        /// <returns></returns>
        public static void SetProperty(object obj, Dictionary <string, object> di)
        {
            if (obj != null)
            {
                var holder = GetHolder(obj.GetType());
                foreach (var kp in di)
                {
                    SetHandler setter = null;
                    holder.Setters.TryGetValue(kp.Key, out setter);
                    if (setter == null)
                    {
                        continue;
                    }

                    var  property = holder.PropInfos[kp.Key];
                    Type t        = Nullable.GetUnderlyingType(property.PropertyType)
                                    ?? property.PropertyType;

                    try
                    {
                        setter(obj, (kp.Value == null) ? null
                                     : Convert.ChangeType(kp.Value, t));
                    }
                    catch (Exception ex)
                    {
                        throw new ArgumentException(string.Format("属性'{0}' ({1})设置值'{2}' ({3})发生异常",
                                                                  kp.Key, t.Name, kp.Value, kp.Value == null ? "null" : kp.Value.GetType().Name
                                                                  ), kp.Key, ex);
                    }
                }
            }
        }
Exemplo n.º 2
0
        public NameTable(Dictionary <string, Named> baseLvl, TypingPolicies typing, RetrievalPolicies retrieval)
        {
            _payload = new List <Dictionary <string, Named> >();
            _payload.Add(baseLvl);

            switch (typing)
            {
            case TypingPolicies.STRONG:
                HandleSettingConflict = EnforceTyping;
                break;

            case TypingPolicies.WEAK:
                HandleSettingConflict = SetValueAndReturnTrue;
                break;
            }

            switch (retrieval)
            {
            case RetrievalPolicies.STRICT:
                HandleDeclareConflict = ReturnFalse;
                HandleMissingVariable = PassThrough;
                break;

            case RetrievalPolicies.LOOSE:
                HandleDeclareConflict = SetValueAndReturnTrue;
                HandleMissingVariable = ProvideAndReturnTrue;
                break;
            }
        }
Exemplo n.º 3
0
        internal static Accessors GetAccessors(PropertyInfo member)
        {
            if (AccessorsCacheCheck.PropertiesDisabled)
            {
                return(new Accessors(inst => Helpers.GetPropertyValue(member, inst), (inst, v) => member.SetValue(inst, v, null)));
            }
            Accessors accessors;

            lock (Properties)
            {
                if (Properties.TryGetValue(member, out accessors))
                {
                    return(accessors);
                }
            }

            GetHandler getter = DynamicMethodCompiler.CreateGetHandler(member.ReflectedType, member) ?? (inst => Helpers.GetPropertyValue(member, inst));
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(member.ReflectedType, member) ?? ((inst, v) => member.SetValue(inst, v, null));

            accessors = new Accessors(getter, setter);

            lock (Properties)
                Properties[member] = accessors;

            return(accessors);
        }
Exemplo n.º 4
0
        public static void SetProperty(object obj, string name, object value)
        {
            if (obj == null || string.IsNullOrWhiteSpace(name))
            {
                return;
            }

            var holder = GetHolder(obj.GetType());

            SetHandler setter = null;

            holder.Setters.TryGetValue(name, out setter);
            if (setter == null)
            {
                return;
            }

            var  property = holder.PropInfos[name];
            Type t        = Nullable.GetUnderlyingType(property.PropertyType)
                            ?? property.PropertyType;

            try
            {
                setter(obj, (value == null) ? null
                             : Convert.ChangeType(value, t));
            }
            catch (Exception ex)
            {
                throw new ArgumentException(string.Format("属性'{0}' ({1})设置值'{2}' ({3})发生异常",
                                                          name, t.Name, value, value == null ? "null" : value.GetType().Name
                                                          ), name, ex);
            }
        }
Exemplo n.º 5
0
        public List <string> FillCardPoolWithSets(int setsAmount, SetHandler setHandler)
        {
            List <string> ret = new List <string>();

            this.upgrades = new List <Upgrade>();

            List <string> packagesList = new List <string>();

            foreach (var package in setHandler.Sets)
            {
                packagesList.Add(package.Key);
            }

            packagesList = packagesList.OrderBy(x => GameHandler.randomGenerator.Next()).ToList();

            for (int i = 0; i < setsAmount && i < packagesList.Count(); i++)
            {
                ret.Add(packagesList[i]);
                for (int j = 0; j < setHandler.Sets[packagesList[i]].Count(); j++)
                {
                    this.upgrades.Add((Upgrade)setHandler.Sets[packagesList[i]][j].DeepCopy());
                }
            }

            this.FillSpareParts();
            this.FillTokens();

            this.GenericMinionPollSort();

            return(ret);
        }
Exemplo n.º 6
0
 public MemberMap(PropertyInfo propertyInfo)
 {
     MemberInfo = propertyInfo;
     Type       = propertyInfo.PropertyType;
     Getter     = createGetHandler(propertyInfo);
     Setter     = createSetHandler(propertyInfo);
 }
Exemplo n.º 7
0
        internal static Accessors GetAccessors(FieldInfo member)
        {
            if (AccessorsCacheCheck.PropertiesDisabled)
            {
                return(new Accessors(member.GetValue, member.SetValue));
            }
            Accessors accessors;

            lock (Fields)
            {
                if (Fields.TryGetValue(member, out accessors))
                {
                    return(accessors);
                }
            }

            GetHandler getter = DynamicMethodCompiler.CreateGetHandler(member.ReflectedType, member) ?? member.GetValue;
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(member.ReflectedType, member) ?? member.SetValue;

            accessors = new Accessors(getter, setter);

            lock (Fields)
                Fields[member] = accessors;

            return(accessors);
        }
Exemplo n.º 8
0
        public static SetHandler CreateSetHandler(Type type, PropertyInfo propertyInfo)
        {
            lock (AppInfo.SetDictionary)
            {
                if (AppInfo.SetDictionary.ContainsKey(propertyInfo))
                {
                    return(AppInfo.SetDictionary[propertyInfo]);
                }
                else
                {
                    MethodInfo    setMethodInfo = propertyInfo.GetSetMethod(true);
                    DynamicMethod dynamicSet    = CreateSetDynamicMethod(type);
                    ILGenerator   setGenerator  = dynamicSet.GetILGenerator();

                    setGenerator.Emit(OpCodes.Ldarg_0);
                    setGenerator.Emit(OpCodes.Ldarg_1);
                    Unbox(setMethodInfo.GetParameters()[0].ParameterType, setGenerator);
                    setGenerator.Emit(OpCodes.Call, setMethodInfo);
                    setGenerator.Emit(OpCodes.Ret);

                    SetHandler setHandler = (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
                    AppInfo.SetDictionary.Add(propertyInfo, setHandler);
                    return(setHandler);
                }
            }
        }
Exemplo n.º 9
0
 public MemberMap(FieldInfo fieldInfo)
 {
     MemberInfo = fieldInfo;
     Type       = fieldInfo.FieldType;
     Getter     = createGetHandler(fieldInfo);
     Setter     = createSetHandler(fieldInfo);
 }
        public FieldAccessor(FieldInfo fieldInfo) : base(fieldInfo.Name, fieldInfo.FieldType)
        {
            _fieldInfo  = fieldInfo;
            _getHandler = DelegateFactory.CreateGet(fieldInfo);
            _setHandler = DelegateFactory.CreateSet(fieldInfo);

            _isInternal = _fieldInfo.IsPrivate || _fieldInfo.IsFamily;
        }
Exemplo n.º 11
0
 private void PredProcess(string name, SetHandler set, string path)
 {
     CheckDirectory(set, path, ProcessEncrypt, name);
     while (IsFileLocked(Path.Combine(this.path.SourcePath, path, name)))
     {
         ;
     }
 }
Exemplo n.º 12
0
 private void CheckDirectory(SetHandler Set, string directoryName, ProcessHandler process, string fileName)
 {
     if (!Directory.Exists(Path.Combine(path.SourcePath, directoryName)))
     {
         Set("ErrorDirectory");
         process(fileName);
     }
 }
Exemplo n.º 13
0
 public InterpolateFromCurrent(InterpolateHandler InterpolateFunction, ITimer timer,
                               SetHandler SetCallback, GetHandler GetCallback)
 {
     this.InterpolateFunction = InterpolateFunction;
     this.timer = timer;
     timer.SubscribeToTicked(TimerTicked);
     timer.SubscribeToFinished(TimerFinished);
     Set = SetCallback;
     Get = GetCallback;
 }
Exemplo n.º 14
0
 public GameHandler()
 {
     this.players = new List <Player>();
     this.pool    = new MinionPool();
     this.pool.FillGenericMinionPool();
     this.setHandler            = new SetHandler();
     this.pairsHandler          = new PairsHandler();
     this.combatOutputCollector = new CombatOutputCollector();
     this.shopRarities          = new RarityBreakdown(4, 3, 2, 1);
 }
Exemplo n.º 15
0
    public override void OnInspectorGUI()
    {
        SetHandler _target = target as SetHandler;

        EditorGUILayout.BeginVertical();
        GUIContent setLabel = new GUIContent("Running Set");

        EditorGUILayout.PropertyField(serializedObject.FindProperty("runningSet"), setLabel);
        EditorGUILayout.HelpBox("Current object count: " + _target.runningSet.Count.ToString(), MessageType.Info);
        EditorGUILayout.EndVertical();
    }
Exemplo n.º 16
0
 public AttributeInfo()
 {
     this.columnIndex = 0;
     this.columnName = "";
     this.columnType = DbType.Object;
     this.primaryKey = false;
     this.autoIncrement = false;
     this.nullable = true;
     this.property = null;
     this.setPropertyHandler = null;
 }
Exemplo n.º 17
0
        private DateTimeResolutionResult ParseEachUnit(string text)
        {
            var ret = new DateTimeResolutionResult();

            // handle "daily", "weekly"
            var match = this.config.PeriodicRegex.Match(text);

            if (match.Success)
            {
                // @TODO refactor to pass match
                if (!this.config.GetMatchedDailyTimex(text, out string timex))
                {
                    return(ret);
                }

                ret = SetHandler.ResolveSet(ref ret, timex);

                return(ret);
            }

            // handle "each month"
            var exactMatch = this.config.EachUnitRegex.MatchExact(text, trim: true);

            if (exactMatch.Success)
            {
                var sourceUnit = exactMatch.Groups["unit"].Value;
                if (string.IsNullOrEmpty(sourceUnit))
                {
                    sourceUnit = exactMatch.Groups["specialUnit"].Value;
                }

                if (!string.IsNullOrEmpty(sourceUnit) && this.config.UnitMap.ContainsKey(sourceUnit))
                {
                    // @TODO refactor to pass match
                    if (!this.config.GetMatchedUnitTimex(sourceUnit, out string timex))
                    {
                        return(ret);
                    }

                    // "handle every other month"
                    if (exactMatch.Groups["other"].Success)
                    {
                        timex = timex.Replace("1", "2");
                    }

                    ret = SetHandler.ResolveSet(ref ret, timex);
                }
            }

            return(ret);
        }
Exemplo n.º 18
0
        public static void SetPropertyValue(Object obj, PropertyInfo property, Object value)
        {
            //创建Set委托
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(obj.GetType(), property);

            //先获取该私有成员的数据类型
            Type type = property.PropertyType;

            //通过数据类型转换
            value = TypeUtils.ConvertForType(value, type);

            //将值设置到对象中
            setter(obj, value);
        }
Exemplo n.º 19
0
        public static void SetFieldValue(Object obj, FieldInfo field, Object value)
        {
            //创建Set委托
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(obj.GetType(), field);

            //先获取该私有成员的数据类型
            Type type = field.FieldType;

            //通过数据类型转换
            value = TypeUtils.ConvertForType(value, type);

            //将值设置到对象中
            setter(obj, value);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes the property and generates the implementation for getter and setter methods.
        /// </summary>
        public FastPropertyInfo(PropertyInfo property)
        {
            this.property = property;

            if (property.CanWrite)
            {
                setValueImpl = DynamicMethodCompiler.CreateSetHandler(property.DeclaringType, property);
            }

            if (property.CanRead)
            {
                getValueImpl = DynamicMethodCompiler.CreateGetHandler(property.DeclaringType, property);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes the property and generates the implementation for getter and setter methods.
        /// </summary>
        public FastPropertyInfo(PropertyInfo property)
        {
            this.property = property;

            if (property.CanWrite)
            {
                setValueImpl = DynamicMethodCompiler.CreateSetHandler(property.DeclaringType, property);
            }

            if (property.CanRead)
            {
                getValueImpl = DynamicMethodCompiler.CreateGetHandler(property.DeclaringType, property);
            }
        }
        GetCachedSetFieldHandlerDelegate(Type type, FieldInfo fieldInfo)
        {
            int intCachedKey = fieldInfo.GetHashCode();//type.ToString() + "|F|" + fieldInfo.Name;

            if (_fieldSetDelegates.ContainsKey(intCachedKey))
            {
                return((SetHandler)_fieldSetDelegates[intCachedKey]);
            }

            SetHandler returnValue = CreateSetHandler(type, fieldInfo);

            lock (_fieldSetDelegates)
            {
                _fieldSetDelegates[intCachedKey] = returnValue;
            }
            return(returnValue);
        }
        GetCachedSetPropertyHandlerDelegate(Type type, PropertyInfo propertyInfo)
        {
            int intCachedKey = propertyInfo.GetHashCode();//type.ToString() + "|P|" + propertyInfo.Name;

            if (_propertySetDelegates.ContainsKey(intCachedKey))
            {
                return((SetHandler)_propertySetDelegates[intCachedKey]);
            }

            SetHandler returnValue = CreateSetHandler(type, propertyInfo);

            lock (_propertySetDelegates)
            {
                _propertySetDelegates[intCachedKey] = returnValue;
            }
            return(returnValue);
        }
Exemplo n.º 24
0
        private DateTimeResolutionResult ParseEach(IDateTimeExtractor extractor, IDateTimeParser parser, string text, DateObject refDate)
        {
            var ret = new DateTimeResolutionResult();

            List <ExtractResult> ers = null;
            var success = false;

            // remove key words of set type from text
            var match = config.SetEachRegex.Match(text);

            if (match.Success)
            {
                var trimmedText = text.Remove(match.Index, match.Length);

                ers = extractor.Extract(trimmedText, refDate);
                if (ers.Count == 1 && ers.First().Length == trimmedText.Length)
                {
                    success = true;
                }
            }

            // remove suffix 's' and "on" if existed and re-try
            match = this.config.SetWeekDayRegex.Match(text);
            if (match.Success)
            {
                var trimmedText = text.Remove(match.Index, match.Length);

                trimmedText = trimmedText.Insert(match.Index, config.WeekDayGroupMatchString(match));

                ers = extractor.Extract(trimmedText, refDate);
                if (ers.Count == 1 && ers.First().Length == trimmedText.Length)
                {
                    success = true;
                }
            }

            if (success)
            {
                var pr = parser.Parse(ers[0], refDate);

                ret = SetHandler.ResolveSet(ref ret, pr.TimexStr);
            }

            return(ret);
        }
Exemplo n.º 25
0
        public static void SetValue(BusinessObject obj, PropertyInfo proInfo, object value)
        {
            string key = obj.AATableName + proInfo.Name;

            try
            {
                SetHandler setHandler = null;
                if (lstSetHandler.TryGetValue(key, out setHandler) == false)
                {
                    setHandler = ABCDynamicMethodCompiler.CreateSetHandler(obj.GetType(), proInfo);
                    lstSetHandler.Add(key, setHandler);
                }
                setHandler(obj, value);
            }
            catch (System.Exception ex)
            {
                proInfo.SetValue(obj, value, null);
            }
        }
Exemplo n.º 26
0
        public static void SetValue(BusinessObject obj, String strColName, object value)
        {
            string key = obj.AATableName + strColName;

            try
            {
                SetHandler setHandler = null;
                if (lstSetHandler.TryGetValue(key, out setHandler) == false)
                {
                    Type type = obj.GetType();

                    PropertyInfo proInfo = BusinessObjectHelper.GetProperty(obj.AATableName, strColName);
                    if (proInfo == null)
                    {
                        proInfo = type.GetProperty(strColName);
                    }

                    setHandler = ABCDynamicMethodCompiler.CreateSetHandler(type, proInfo);
                    lstSetHandler.Add(key, setHandler);
                }

                if (value is String && value.ToString().Replace("'", "").ToUpper() == "TRUE")
                {
                    value = true;
                }
                else if (value is String && value.ToString().Replace("'", "").ToUpper() == "FALSE")
                {
                    value = false;
                }
                setHandler(obj, value);
            }
            catch (System.Exception ex)
            {
                PropertyInfo proInfo = obj.GetType().GetProperty(strColName);
                if (proInfo == null)
                {
                    //    Utilities.ABCLogging.LogNewMessage( "ABCDataLib" , "" , "SetValue" , obj.GetType().Name+" not contain "+strColName , "FAILE" );
                    return;
                }
                proInfo.SetValue(obj, value, null);
            }
        }
Exemplo n.º 27
0
        private DateTimeResolutionResult ParseEachUnit(string text)
        {
            var ret = new DateTimeResolutionResult();

            // handle "each month"
            var match = this.config.EachUnitRegex.MatchExact(text, trim: true);

            if (match.Success)
            {
                var sourceUnit = match.Groups["unit"].Value;
                if (!string.IsNullOrEmpty(sourceUnit) && this.config.UnitMap.ContainsKey(sourceUnit))
                {
                    if (this.config.GetMatchedUnitTimex(sourceUnit, out string timexStr))
                    {
                        ret = SetHandler.ResolveSet(ref ret, timexStr);
                    }
                }
            }

            return(ret);
        }
Exemplo n.º 28
0
        private DateTimeResolutionResult ParseEachDuration(string text, DateObject refDate)
        {
            var ret = new DateTimeResolutionResult();

            var ers = this.config.DurationExtractor.Extract(text, refDate);

            if (ers.Count != 1 || string.IsNullOrWhiteSpace(text.Substring(ers[0].Start + ers[0].Length ?? 0)))
            {
                return(ret);
            }

            var afterStr = text.Substring(ers[0].Start + ers[0].Length ?? 0);

            if (this.config.EachPrefixRegex.IsMatch(afterStr))
            {
                var pr = this.config.DurationParser.Parse(ers[0], DateObject.Now);
                ret = SetHandler.ResolveSet(ref ret, pr.TimexStr);
                return(ret);
            }

            return(ret);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Creates new <see cref="PropertyBinder"/>, bject that copies value of a
        /// property from one object to another object each time the value
        /// changes.
        /// </summary>
        /// <param name="source">Source object</param>
        /// <param name="target">Target object</param>
        /// <param name="sourceField">Field of the <paramref name="source"/> that is bound to <paramref name="targetField"/></param>
        /// <param name="targetField">Field of the <paramref name="target"/> that recieves updated values of from <paramref name="sourceField"/></param>
        public PropertyBinder(INotifyPropertyChanged source, object target, string sourceField, string targetField, Dictionary <KeyValuePair <Type, string>, GetHandler> getCache, Dictionary <KeyValuePair <Type, string>, SetHandler> setCache)
        {
            Source      = source;
            Target      = target;
            SourceField = sourceField;
            TargetField = targetField;

            Source.PropertyChanged += Source_PropertyChanged;
            KeyValuePair <Type, string> keyGet = new KeyValuePair <Type, string>(source.GetType(), sourceField);
            KeyValuePair <Type, string> keySet = new KeyValuePair <Type, string>(target.GetType(), targetField);

            if (getCache.ContainsKey(keyGet))
            {
                sourceGetHandler = getCache[keyGet];
            }
            else
            {
                PropertyInfo sourceProp = Source.GetType().GetProperty(SourceField);
                sourceGetHandler = DynamicMethodCompiler.CreateGetHandler(Source.GetType(), sourceProp);                 /**/
                getCache[keyGet] = sourceGetHandler;
            }

            if (getCache.ContainsKey(keySet))
            {
                targetSetHandler = setCache[keySet];
            }
            if (targetSetHandler == null)
            {
                PropertyInfo targetProp = Target.GetType().GetProperty(TargetField);                     /**/
                targetSetHandler = DynamicMethodCompiler.CreateSetHandler(Target.GetType(), targetProp); /**/
                setCache[keySet] = targetSetHandler;
            }

            //Debug.Assert(sourceProp != null, "Source property not found");
            //Debug.Assert(targetProp != null, "Target property not found");

            Source_PropertyChanged(null, new PropertyChangedEventArgs(SourceField));
        }
Exemplo n.º 30
0
        private DateTimeResolutionResult ParserTimeEveryday(string text, DateObject refDate)
        {
            var ret = new DateTimeResolutionResult();

            var ers = this.config.TimeExtractor.Extract(text, refDate);

            if (ers.Count != 1)
            {
                return(ret);
            }

            var afterStr = text.Replace(ers[0].Text, string.Empty);
            var match    = this.config.EachDayRegex.Match(afterStr);

            if (match.Success)
            {
                var pr = this.config.TimeParser.Parse(ers[0], DateObject.Now);

                ret = SetHandler.ResolveSet(ref ret, pr.TimexStr);
            }

            return(ret);
        }
Exemplo n.º 31
0
        private DateTimeResolutionResult ParseEach(IDateTimeExtractor extractor, IDateTimeParser parser, string text, DateObject refDate)
        {
            var ret     = new DateTimeResolutionResult();
            var ers     = extractor.Extract(text, refDate);
            var success = false;

            foreach (var er in ers)
            {
                var beforeStr = text.Substring(0, er.Start ?? 0);
                var match     = this.config.EachPrefixRegex.Match(beforeStr);

                if (match.Success && match.Length + er.Length == text.Length)
                {
                    success = true;
                }
                else if (er.Type == Constants.SYS_DATETIME_TIME || er.Type == Constants.SYS_DATETIME_DATE)
                {
                    // Cases like "every day at 2pm" or "every year on April 15th"
                    var eachRegex = er.Type == Constants.SYS_DATETIME_TIME ? this.config.EachDayRegex : this.config.EachDateUnitRegex;
                    match = eachRegex.Match(beforeStr);
                    if (match.Success && match.Length + er.Length == text.Length)
                    {
                        success = true;
                    }
                }

                if (success)
                {
                    var pr = parser.Parse(er, refDate);
                    ret = SetHandler.ResolveSet(ref ret, pr.TimexStr);
                    break;
                }
            }

            return(ret);
        }
Exemplo n.º 32
0
        // CreateSetDelegate
        public static SetHandler CreateSetHandler(Type type, PropertyInfo propertyInfo)
        {
            string _key = string.Format("{0}.{1}", propertyInfo.DeclaringType, propertyInfo.ToString());

            if (s_SetHandlerCache.ContainsKey(_key))
            {
                return(s_SetHandlerCache[_key] as SetHandler);
            }

            MethodInfo    setMethodInfo = propertyInfo.GetSetMethod(true);
            DynamicMethod dynamicSet    = CreateSetDynamicMethod(type);
            ILGenerator   setGenerator  = dynamicSet.GetILGenerator();

            setGenerator.Emit(OpCodes.Ldarg_0);
            setGenerator.Emit(OpCodes.Ldarg_1);
            UnboxIfNeeded(setMethodInfo.GetParameters()[0].ParameterType, setGenerator);
            setGenerator.Emit(OpCodes.Call, setMethodInfo);
            setGenerator.Emit(OpCodes.Ret);

            SetHandler _newHandler = (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));

            s_SetHandlerCache.Add(_key, _newHandler);
            return(_newHandler);
        }