是否可以使用 AutoMapper 来包装方法?
我有两个类:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您说您需要将“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).
您无法将方法映射为目标,只能映射到源(使用自定义投影):
但是绝对没有办法“映射”
void
方法到另一个void
方法。这确实没有意义;映射涉及从一个位置读取和写入到另一个位置,并且您无法从void
方法“读取”值。You can't map to a method as the target, only the source (using a custom projection):
But there's absolutely no way you can "map" a
void
method to anothervoid
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 avoid
method.