美文网首页
C#利用“特性”将实体类生成csv文件

C#利用“特性”将实体类生成csv文件

作者: 浅谈码生活 | 来源:发表于2020-09-24 16:29 被阅读0次

1.根据要生成的csv来构造我们的Attribute:

//标签
public class TagNameAttribute : Attribute
{
    public string TagName
    {
        get;
        set;
    }
    public TagNameAttribute(string tagName)
    {
        TagName = tagName;
    }
}
//备注
public class RematkAttribute : Attribute 
{
    public string Remark { get; set; }

    public RematkAttribute(string remark) 
    {
        Remark = remark;
    }
}

2.将实体类及类属性进行标记特性:

    [TagName("*配置信息")]
    [Rematk("备注")]
    public class TableConfig
    {   
        /// <summary>
        /// 配置类型 默认插入新数据
        /// </summary>
        [TagName("配置类型")]
        [Rematk("(1-删除所有数据、2-删除时间周期数据、3-直插入最新数据、99-自定义任务)")]
        public int JobType { get; set; }
        /// <summary>
        /// 是否为时间时序表 默认为True
        /// </summary>
        public bool IsTimeSeries = true;
        /// <summary>
        /// 删除数据周期时间
        /// </summary>
        [TagName("删除数据周期时间")]
        [Rematk("(以秒为单位)")]
        public int? DelectCycle { get; set; }
        private int refreshCycle = 60;
        /// <summary>
        /// 巡检周期
        /// </summary>
        [TagName("刷新周期")]
        [Rematk("(以秒为单位)")]
        public int RefreshCycle
        {
            get 
            {
                return refreshCycle;
            }
            set 
            {
                refreshCycle = value;
            }
        }
}

3.将实体类解析到CSV文件中:

public static void SaveConfigModel(string fileName, object obj)
{
    string name;
    List<string> props = new List<string>();
    List<List<string>> items = new List<List<string>>();
    object[] objs = obj.GetType().GetCustomAttributes(typeof(TagNameAttribute), true);
    //类不包含TagName特性或者文件中没有TagName项 返回null
    if (objs == null || objs.Length == 0)
    {
        return;
    }
    object[] robjs = obj.GetType().GetCustomAttributes(typeof(RematkAttribute), true);

    if (robjs != null || robjs.Length > 0)
    {
        name = (objs[0] as TagNameAttribute).TagName + ",," + (robjs[0] as RematkAttribute).Remark;
    }
    else 
    {
        name = (objs[0] as TagNameAttribute).TagName + ",";
    }  
    //遍历属性
    foreach (PropertyInfo propInfo in obj.GetType().GetProperties())
    {
        //属性中不包含 TagName特性 跳出本次循环
        object[] objAttrs = propInfo.GetCustomAttributes(typeof(TagNameAttribute), true);
        object[] objRemarks = propInfo.GetCustomAttributes(typeof(RematkAttribute), true);
        if (objAttrs == null || objAttrs.Length == 0)
        {
            continue;
        }
        object value = propInfo.GetValue(obj, null);

        //如果属性是List类型
        if (value is System.Collections.IList)
        {
            List<string> item = new List<string>();
            items.Add(item);
            item.Add((objAttrs[0] as TagNameAttribute).TagName);


            object objItem = (value as System.Collections.IList).GetType().GetGenericArguments()[0].GetConstructor(new Type[0]).Invoke(null);

            string itemStr = "";
            foreach (PropertyInfo propInfoItem in objItem.GetType().GetProperties())
            {
                object[] objItems = propInfoItem.GetCustomAttributes(typeof(TagNameAttribute), true);
                if (objItems == null || objItems.Length == 0)
                {
                    continue;
                }
                itemStr += (objItems[0] as TagNameAttribute).TagName + ",";
            }
            item.Add(itemStr);


            foreach (object valueItem in (value as System.Collections.IList))
            {
                string valueStr = "";
                foreach (PropertyInfo propInfoItem in valueItem.GetType().GetProperties())
                {
                    object[] objItems = propInfoItem.GetCustomAttributes(typeof(TagNameAttribute), true);
                    if (objItems == null || objItems.Length == 0)
                    {
                        continue;
                    }
                    valueStr += propInfoItem.GetValue(valueItem, null)?.ToString() + ",";
                }
                item.Add(valueStr);
            }
        }
        else
        {
            if (objRemarks == null || objRemarks.Length == 0) 
            {
                props.Add((objAttrs[0] as TagNameAttribute).TagName + "," + (value == null ? "" : value.ToString()) + ",");
            }
            else 
            {
                props.Add((objAttrs[0] as TagNameAttribute).TagName + "," + (value == null ? "" : value.ToString()) + ","+ (objRemarks[0] as RematkAttribute).Remark);
            }                   
        }
    }
    List<string> line = new List<string>();
    line.Add(name);
    line.AddRange(props);
    line.Add("/,");
    items.ForEach(c => { line.AddRange(c); line.Add("/,"); });
    File.WriteAllLines(fileName, line, Encoding.Default);
}

4.客户程序调用:

CsvHelper.SaveConfigModel(apppath + "\\" + tableConfig.FileName + ".csv", tableConfig);
生成文件

相关文章

网友评论

      本文标题:C#利用“特性”将实体类生成csv文件

      本文链接:https://www.haomeiwen.com/subject/pnxtuktx.html