【发布时间】:2018-10-25 16:51:51
【问题描述】:
使用一些现有的 Mapper,是否可以:
var target = Mapper.Map(source).To<Dto>();
其中source 是IEnumerable<(string Foo, int Bar)>,Dto 是具有Foo 和Bar 属性的类?
示例代码:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace MapFromDynamicsToComplex
{
internal class Program
{
private static void Main(string[] args)
{
var source = DataAccessLayer.Method();
//var target = Mapper.Map(source).To<Dto>();
var parameterNames = string.Join(", ", Utilities.GetValueTupleNames(typeof(DataAccessLayer), nameof(DataAccessLayer.Method)));
Console.WriteLine(parameterNames);
Console.ReadKey();
}
}
public class DataAccessLayer
{
public static IEnumerable<(string Foo, int bar)> Method()
{
return new List<(string Foo, int bar)>
{
ValueTuple.Create("A", 1)
};
}
}
public class Dto
{
public string Foo { get; set; }
public int Bar { get; set; }
public object Baz { get; set; }
}
public static class Utilities
{
public static IEnumerable<string> GetValueTupleNames(Type source, string action)
{
var method = source.GetMethod(action);
var attr = method.ReturnParameter.GetCustomAttribute<TupleElementNamesAttribute>();
return attr.TransformNames;
}
}
}
通过使用TupleElementNamesAttribute it is possible 在运行时访问值元组元素,特别是它的名称。
【问题讨论】:
-
自己编写很容易,但您需要告诉 Mapper 方法名称,以便它可以使用
GetValueTupleNames。
标签: c# mapping valuetuple