.net 是否可以使用AutoMapper包装方法?

.net 是否可以使用AutoMapper包装方法?,.net,interface,automapper,sealed,.net,Interface,Automapper,Sealed,我有两门课: public class TestClass1 { public int TestInt { get; set; } public void TestMethod() { // Do something } } public class TestClass2 { public int TestInt { get; set; } public void TestMethod() { // D

我有两门课:

public class TestClass1
{
    public int TestInt { get; set; }

    public void TestMethod()
    {
        // Do something
    }
}

public class TestClass2
{
    public int TestInt { get; set; }

    public void TestMethod()
    {
        // Do something
    }
}
我想创建一个可用于这两个类的接口。最简单的解决方案是在TestClass1和TestClass2上实现接口,但我没有;我无法访问这些类的实现(外部dll)。我想知道是否可以创建新接口,并使用AutoMapper将TestClass1和TestClass2映射到ITestInterface:

public interface ITestInterface
{
    int TestInt { get; set; }

    void TestMethod();
}

您说您需要映射“TestClass1和TestClass2到ITestInterface”,但是您需要映射到的类的实例,因为您无法创建接口的实例


我假设您正试图通过将类转换为相同的接口来交换处理这些类。如果Automapper不是您应该看到的-请参阅此部分,了解有关如何管理将类视为它们都实现了相同接口的详细信息(即使您没有访问源代码的权限)。

您不能将方法映射为目标,只能映射源(使用自定义投影):

Mapper.CreateMap()
.ForMember(dest=>dest.SomeValue,
opt=>opt.MapFrom(src=>src.GetSomeValue())

但是绝对没有办法将一个
void
方法“映射”到另一个
void
方法。这真的没有意义;映射涉及从一个位置读取和写入另一个位置,而您不能从
void
方法中“读取”值。

您是对的,我不能将void映射到void值,但我对返回值不感兴趣。我想映射该方法的执行。类似于:Mapper.CreateMap.FormMember(dest=>dest.DoSomething(),opt=>opt.MapFrom(src=>src.DoSomething())。@Woj:那么您根本不是在谈论映射,而是在谈论包装器或适配器:。只能映射数据。
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.SomeValue, 
        opt => opt.MapFrom(src => src.GetSomeValue()))