Ejemplo n.º 1
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="target">The target to set the value on.</param>
        /// <param name="value">The value to set on the target.</param>
        public void SetValue(object target, object value)
        {
            try
            {
                if (_setter == null)
                {
                    _setter = DynamicReflectionDelegateFactory.Instance.CreateSet <object>(_memberInfo);
                }

                Type underlyingType = ReflectionUtils.GetMemberUnderlyingType(_memberInfo);

                if (!UnityUtilities.IsNull(value))
                {
                    if (ReferenceHandler.IsTypeReference(value.GetType()) && typeof(UnityEngine.Object).IsAssignableFrom(underlyingType))
                    {
                        ReferenceHandler.AssignObjectValue(value, underlyingType, x =>
                        {
                            _setter(target, x);
                        });

                        return;
                    }
                }

#if DEBUG
                // dynamic method doesn't check whether the type is 'legal' to set
                // add this check for unit tests
                if (value == null)
                {
                    if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo)))
                    {
                        throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo));
                    }
                }
                else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType()))
                {
                    throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType()));
                }
#endif

                _setter(target, value);
            }
            catch (Exception ex)
            {
                throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
            }
        }