Set Values to PropertyInfo and FieldInfo - CSharp System.Reflection

CSharp examples for System.Reflection:FieldInfo

Description

Set Values to PropertyInfo and FieldInfo

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;//www .  j a v  a2s  . c o m

public class Main{
        // TODO: Unify with FieldInfo overload
        public static void AddValues(object target, PropertyInfo property, IEnumerable<object> values)
        {
            if (!IsArray(property.PropertyType))
                throw new ArgumentException(nameof(property));

            IList list = property.GetValue(target) as IList;
            if (list == null)
            {
                list = (IList)Activator.CreateInstance(property.PropertyType);
                property.SetValue(target, list);
            }

            foreach (var value in values)
            {
                if (list.Add(value) == -1)
                {
                    throw new ArgumentException($"Could not add value `{value}` to list.");
                }
            }
        }
        public static void AddValues(object target, FieldInfo field, IEnumerable<object> values)
        {
            if (!IsArray(field.FieldType))
                throw new ArgumentException(nameof(field));

            IList list = field.GetValue(target) as IList;
            if (list == null)
            {
                list = (IList)Activator.CreateInstance(field.FieldType);
                field.SetValue(target, list);
            }

            foreach (var value in values)
            {
                if (list.Add(value) == -1)
                {
                    throw new ArgumentException($"Could not add value `{value}` to list.");
                }
            }
        }
}

Related Tutorials