コード例 #1
0
        public static List <T> ParseStringArray <T>(string[] lines) where T : new()
        {
            if (lines == null)
            {
                throw new ArgumentNullException(nameof(lines));
            }

            var list            = new List <T>();
            var props           = typeof(T).GetFixedWidthAttributedProperties();
            var propertyInfos   = props as PropertyInfo[] ?? props.ToArray();
            var minStringLength = Utils.CheckMinStringWidth(propertyInfos);

            foreach (var line in lines)
            {
                // Check if the string has the minimal required length
                if (line.Length < minStringLength)
                {
                    // if it is too short skip this line because we can not
                    // successfully parse the line
                    continue;
                }

                var e = new T();
                foreach (var propertyInfo in propertyInfos)
                {
                    var attribute = propertyInfo.GetFixedWidthAttribute();

                    var toConvert = line.Substring(attribute.From, attribute.Length);

                    // choose the converter to convert
                    var converter = Utils.CreateConverterFromType(attribute.Converter)
                                    ?? ConverterMap.GetForType(propertyInfo.PropertyType);

                    propertyInfo.SetValue(e, Utils.ConvertWithConverter(converter, toConvert));
                }
                list.Add(e);
            }
            return(list);
        }