当抽象类不公开每个构造函数参数时,为什么不能创建相似代理?
本文关键字:不能 为什么 创建 相似 代理 参数 抽象类 构造函数 | 更新日期: 2023-09-27 17:49:27
我非常成功地使用了Ploeh的SemanticComparison库——除非涉及到一个不公开其所有构造函数参数的抽象类。
这里是我得到的例外-
Ploeh.SemanticComparison.ProxyCreationException : The proxy of Foo could not be created using the same semantic heuristics as the default semantic comparison. In order to create proxies of types with non-parameterless constructor the values from the source constructor must be compatible to the parameters of the destination constructor.
----> System.InvalidOperationException : Operation is not valid due to the current state of the object.
这是我能想到的最简单的例子-
// this fails with the aforementioned exception
_fixture.Create<Foo>().AsSource().OfLikeness<Foo>().CreateProxy();
public class Foo : Bar
{
public Foo(int age)
: base(age)
{
}
}
public abstract class Bar
{
private readonly int _age;
protected Bar(int age)
{
_age = age;
}
}
然而,如果我将public int NotAge { get; set; }
添加到抽象类Bar
中,那么一切都很好。我真的认为这是次优解因为我不想暴露属性age
。它只是被用来计算其他东西。
如果不为了测试而暴露属性,我如何解决这个问题?是否有其他库可以实现相同的效果而不会出现这个问题?
当在获取目标类的属性和匹配源类型的构造函数时出现问题时,尽管错误读起来好像只映射了构造函数,但会引发此错误。
在你的例子中,内部异常是由于两个类中都没有公共属性。我很确定你的修复只是将映射重定向到你的虚拟属性。
您可以在基类上使用public int age { get { return _age; } }
来修复它-在本例中几乎没有危害。
InternalVisibleTo
,但是库目前在映射类型时只使用BindingFlags.Public
,因此它不会看到为此目的创建的内部属性。我能够通过调整源代码来使用BindingFlags.NonPublic
和BindingFlags.Public
来创建代理,但我不确定这是一种合理的方法。