Ejemplo n.º 1
0
            /// <summary>
            /// Sets the value of the property, or if it has a NamedCollectionOption, adds it to the collection of the property value.
            /// </summary>
            /// <param name="instance"></param>
            /// <param name="value"></param>
            public void SetValue(object instance, object?value)
            {
                if (AttributeHandler.IsCollectionAttribute(Option))
                {
                    if (value == null)
                    {
                        throw new InvalidOperationException($"The target value for the property \"{PropertyInfo.Name}\" on \"{PropertyInfo.DeclaringType}\" is null, but it is marked as a collection.");
                    }
                    var propertyValue = PropertyInfo.GetValue(instance) ?? throw new InvalidOperationException($"The property \"{PropertyInfo.Name}\" on \"{PropertyInfo.DeclaringType}\" must return an instance.");

                    //TODO: use ICollection for this case, instead of IList.
                    //that way we don't demand both IList and ICollection<>
                    var list = (IList)propertyValue;

                    list.Clear();
                    foreach (var element in (IList)value)
                    {
                        list.Add(element);
                    }
                }
                else
                {
                    PropertyInfo.SetValue(instance, value);
                }
            }
Ejemplo n.º 2
0
            public void SetValue(object?value)
            {
                if (AttributeHandler.IsCollectionAttribute(Option))
                {
                    if (value == null)
                    {
                        throw new InvalidOperationException($"The target value for the property \"{ParameterInfo.Name}\" on \"{MethodName}\" is null, but it is marked as a collection.");
                    }

                    //TODO: Create element of the correct type.
                    if (Value == null)
                    {
                        var constructor = ParameterInfo.ParameterType.GetConstructors().FirstOrDefault((x) => x.IsPublic && x.GetParameters().Length == 0);
                        if (constructor != null)
                        {
                            Value = constructor.Invoke(new object[0]);
                        }
                        else
                        {
                            Value = Activator.CreateInstance(typeof(List <>).MakeGenericType(AttributeHandler.GetValueType(Option, ParameterInfo.ParameterType)));
                        }
                    }

                    var list = (IList)Value;

                    list.Clear();
                    foreach (var element in (IList)value)
                    {
                        list.Add(element);
                    }
                }
                else
                {
                    Value = value;
                }
            }