【问题标题】:Iterate through class properties using an action?使用操作迭代类属性?
【发布时间】:2022-01-19 06:29:31
【问题描述】:

我正在使用CsvHelper 导入csv 文件,为此我使用如下映射类:

private class MyClassMap : ClassMap<MyClass>
{
    public MyClassMap ()
    {
        Map(m => m.Number).Name("Number");
        Map(m => m.Name).Name("Name");
    }
}

大多数类都包含更多属性。所以我首先要做的是创建一个Attribute 类并将该属性添加到所有公共属性中。所以我可以更改映射代码:

private class MyClassMap : ClassMap<MyClass>
{
    public MyClassMap ()
    {
        var properties = typeof(MyClass).GetProperties();
        foreach (var property in properties)
        {
            var attr = property.GetCustomAttributes(typeof(HeaderAttribute), false).FirstOrDefault();
            if (attr != null)
            {
               //Here what?
            }
        }
    }
}

另外,我将把上面的ctor代码变成一个扩展方法。

在这种情况下我将如何使用Map() 方法?

【问题讨论】:

    标签: c# linq reflection csvhelper


    【解决方案1】:

    假设您的 HeaderAttribute 接受 Header 作为参数并将其暴露在 Header 属性上:

        foreach (var property in properties)
        {
            var attr = property.GetCustomAttributes(typeof(HeaderAttribute), false).FirstOrDefault() as HeaderAttribute;
            if (attr != null)
            {
               //Here we use the Map method overload that takes a Type and a MemberInfo
    
                this.Map(typeof(MyClass), property).Name(attr.Header);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2016-06-30
      • 2016-06-18
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多