将AutoMapper与带有静态工厂方法的值对象一起使用的最佳方法是:

public class ImmutableDetail
{
  public static ImmutableDetail Create(string detail) => new ImmutableDetail(detail);

      private ImmutableDetail(string detail)
      {
         Detail = detail;
      }

      public string Detail { get;}

    }


我希望能够:

var immutableDetails = Mapper.Map<ImmutableDetail>(source);

最佳答案

有以下课程:

public class DummySource
{
    public string Detail { get; set; }
}

public class ImmutableDetail
{
    public static ImmutableDetail Create(string detail) { return new ImmutableDetail(detail); }

    private ImmutableDetail(string detail)
    {
        Detail = detail;
    }

    public string Detail { get; private set; }
}


您可以进行如下映射:

Mapper.CreateMap<DummySource, ImmutableDetail>().ConstructUsing((DummySource ds) => ImmutableDetail.Create(ds.Detail));
var source = new DummySource { Detail = "Hello" };
var immutableDetails = Mapper.Map<ImmutableDetail>(source);

关于c# - 具有静态工厂方法的AutoMapper,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40883375/

10-10 15:35