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

发布于 2024-08-30 01:26:45 字数 577 浏览 5 评论 0原文

我有两个类:

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();
}

I have two classes:

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
    }
}

I want to create interface that I can use for both classes. The easiest solution is to implement the interface on TestClass1 and TestClass2 but I don;t have access to the implementation of these classes (external dll). I was wondering if I can create new interface and use AutoMapper to map TestClass1 and TestClass2 to ITestInterface:

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

    void TestMethod();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青萝楚歌 2024-09-06 01:26:45

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

我假设您试图通过将这些类转换为相同的接口来互换地处理这些类。如果是这样,Automapper 不是您应该关注的 - 请参阅此 有关堆栈溢出的问题,了解有关如何管理将这些类视为都实现相同接口的一些详细信息(即使您无权访问源代码)。

You say you require mapping "TestClass1 and TestClass2 to ITestInterface", however you'd need an instance of a class to map to as you can't create an instance of an interface.

I assume you're trying to treat the classes interchangeably by converting them to the same interface. If so Automapper isn't what you should be looking at - see this question on stack-overflow for some details on how to manage treating the classes as if they both implement the same interface (even if you don't have access to the source code).

思念满溢 2024-09-06 01:26:45

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

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

但是绝对没有办法“映射”void 方法到另一个 void 方法。这确实没有意义;映射涉及从一个位置读取写入到另一个位置,并且您无法从void方法“读取”值。

You can't map to a method as the target, only the source (using a custom projection):

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

But there's absolutely no way you can "map" a void method to another void method. It doesn't really make sense; mapping involves reading from one place and writing to another, and you can't "read" a value from a void method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文