繁体   English   中英

CsvHelper.Configuration.ClassMap 的动态分配属性<t></t>

[英]Dynamic assigned Properties for CsvHelper.Configuration.ClassMap<T>

我想通过动态分配的属性来使用CsvHelper.Configuration.ClassMap

通常你 map 以 static 方式这样的属性:你必须分配每个属性及其“要显示的文本”。

using CsvHelper.Configuration;

        public sealed class CleanSQLRowDescriptorMap : ClassMap<CleanSQLRowDescriptor>
        {
            public CleanSQLRowDescriptorMap()
            {
                Map(f => f.OriginalIndex).Name("Original Index");
                Map(f => f.OriginalRow).Name("Original Row");
            }
       }

我想做以下事情:

using CsvHelper.Configuration;

        public sealed class CleanSQLRowDescriptorMap : ClassMap<CleanSQLRowDescriptor>
        {
            public CleanSQLRowDescriptorMap()
            {
                // Filter by attribute (implementation returns PropertyInfo List)
                List<PropertyInfo> mappedProperties = CleanSQLRowDescriptor.Create().FilterPropertiesByAttribute();

                // Dynamically assign each property and its assigned 'attribute value'  
                // At the moment I mapped the PropertyInfo.Name, but I actually need to use the Property as the static example above.  
                // Also need to figure out how to get the Attribute value (DisplayName in this example).
                mappedProperties.ForEach(prop => Map(f => prop.Name).Name(prop.Name));
            }
       }

我目前有上面使用的以下方法:

            [DisplayName("Original Index")]
            public int OriginalIndex { get; set; }

            [DisplayName("Original Row")]
            public string OriginalRow { get; set; }

            public string DonotWantToAssignThis { get; set; }

            public List<PropertyInfo> FilterPropertiesByAttribute()
            {
                // This function already returns only the attributes that use
                // [DisplayName] and other attributes defined for other properties, 
                // ignoring other properties that do not have any of these attributes.

                return properties;
            }

如何使用 PropertyInfo 项目列表来动态分配 ClassMap? 我想创建一个基本 class 并将这些属性作为过滤器,并且实现此基本 class 的所有类都将具有相同的功能,从而更容易“维护映射”。

我设法弄清楚了,VS Code 没有给我Map() function 的所有重载,所以我错过了重载。

在所有示例中都使用了这个:

MemberMap<TClass, TMember> Map<TMember>(Expression<Func<TClass, TMember>> expression, bool useExistingMap = true);

我在JoshClose/CSVHelper中找到了这个:

public MemberMap Map(Type classType, MemberInfo member, bool useExistingMap = true)

因此,我现在可以直接分配MemberInfo ,而不是使用不采用类型的“需要属性名称为 TMember 的表达式”。

下面的代码仅显示了使用其.DisplayName 属性值的单个属性 [DisplayName]的解决方案。
对于我目前拥有的其他属性,我需要以不同的方式处理属性值:

mappedProperties.ForEach(prop =>
{
   Map(typeof(CleanSQLRowDescriptor), prop).Name(prop.GetCustomAttribute<DisplayNameAttribute>().DisplayName);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM