示例#1
0
        /// <summary>
        /// Map from the provided arguments onto the public properties of an existing
        /// object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="args"></param>
        /// <param name="obj"></param>
        public static void MapOnto <T>(IArguments args, T obj)
        {
            var targetType       = typeof(T);
            var publicProperties = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                   .Where(p => p.CanWrite && p.SetMethod != null)
                                   .ToList();

            foreach (var property in publicProperties)
            {
                // Try to map positional argument if the attribute is set
                var attr = property.GetCustomAttributes <ArgumentIndexAttribute>(true).FirstOrDefault();
                if (attr != null)
                {
                    var index = attr.Index;
                    var positionalArgument = args.Consume(index);
                    AssignPropertyValue(positionalArgument, property, obj);
                    continue;
                }

                if ((property.PropertyType == typeof(bool) || property.PropertyType == typeof(bool?)) && args.ConsumeFlag(property.Name).Exists())
                {
                    property.SetValue(obj, true);
                    continue;
                }

                var namedArg = args.Consume(property.Name);
                if (namedArg.Exists())
                {
                    AssignPropertyValue(namedArg, property, obj);
                }
            }
        }