示例#1
0
        /// <summary>
        /// To be added.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="line"></param>
        /// <param name="cultureInfo"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public static T CsvObjectFromLine <T>(this string line, CultureInfo cultureInfo, string separator) where T : class, new()
        {
            string[] words  = line.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
            T        result = new();

            List <PropertyInfo> properties = result.GetType().GetProperties(BindingFlagsConstraint)
                                             .Where(p => p.CanWrite && !p.CustomAttributes.Any(a => a.AttributeType == typeof(CsvIgnoreAttribute)))
                                             .ToList();

            for (var index = 0; index < properties.Count; index++)
            {
                PropertyInfo prop  = properties[index];
                string       value = words[index];

                IConvertFormat formatter = prop.GetFormatter();

                if (formatter == null)
                {
                    prop.SetValue(result, Convert.ChangeType(value, prop.PropertyType, cultureInfo), cultureInfo);
                }
                else
                {
                    prop.SetValue(result, formatter.Convert(value, cultureInfo), cultureInfo);
                }
            }

            return(result);
        }
示例#2
0
        /// <summary>
        /// To be added.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cultureInfo"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public static string CsvLineFromObject <T>(this T obj, CultureInfo cultureInfo, string separator) where T : class
        {
            var result = new List <string>();

            IEnumerable <PropertyInfo> properties = obj.GetType().GetProperties(BindingFlagsConstraint)
                                                    .Where(p => p.CanWrite && !p.CustomAttributes.Any(a => a.AttributeType == typeof(CsvIgnoreAttribute)));

            foreach (var prop in properties)
            {
                object value = prop.GetValue(obj, cultureInfo);

                IConvertFormat formatter = prop.GetFormatter();

                if (formatter == null)
                {
                    result.Add(value is IConvertible ? (value as IConvertible).ToString(cultureInfo) : value.ToString());
                }
                else
                {
                    result.Add(formatter.ConvertBack(value, cultureInfo));
                }
            }

            return(string.Join(separator, result));
        }