I have the following method in public abstract A : IVirtualMachineExporter
:
public override void Prepare() { ... }
I call the Prepare
from another class B
:
public sealed class B
{
public new ExportJobRequest Request { get { return (ExportJobRequest)base.Request; } }
private void ExportTask()
{
IVirtualMachineExporter exporter = CreateExporter();
exporter.Prepare();
}
}
Request
containing public bool isAdHoc { get; set; }
. I want to use information from this property inside Prepare()
. How can I do this? I don't want to change Prepare()
signature.
答案 0 :(得分:2)
如何在不更改准备签名的情况下执行此操作?
嗯,某种程度上 Prepare
需要一个实例来调用isAdHoc
,所以如果你不想改变方法签名,您可以更改类或界面吗?
类似的东西:
IVirtualMachineExporter exporter = CreateExporter(Request);
exporter.Prepare();
或
IVirtualMachineExporter exporter = CreateExporter();
exporter.Request = Request;
exporter.Prepare();
答案 1 :(得分:0)
在A类中,公开一个公共属性IsAdhoc。
在从B类调用Prepare之前,在A类上设置IsAdhoc属性。
因此...
A类
public bool IsAdhoc { get; set; }
// Inside this method, do something based on the IsAdhoc property above.
public override void Prepare() { ... }
B类
public sealed class B
{
public new ExportJobRequest Request { get { return (ExportJobRequest)base.Request; } }
private void ExportTask()
{
IVirtualMachineExporter exporter = CreateExporter();
exporter.IsAdhoc = this.Request.isAdhoc;
exporter.Prepare();
}
}
或者,您可以将布尔值传递给CreateExporter方法,该方法可以通过其构造函数在新的导出器类上设置它。
答案 2 :(得分:0)
看起来B
取决于IVirtualMachineExporter
,而IVirtualMachineExporter
(A
)的实施取决于Request
。
B
不应该对A
或它所依赖的内容有所了解。它应该只关心IVirtualMachineExporter
接口并调用Prepare()
。
您可以像这样创建:
public abstract class A : IVirtualMachineExporter
{
private readonly ExportJobRequest _request;
public A(ExportJobRequest request)
{
_request = request;
}
public override void Prepare()
{
//Now Prepare() has access to the Request because
//it's contained within A, the class that actually needs it.
}
}
同样,将接口(不是具体实现)传递给B
。
public sealed class B
{
private readonly IVirtualMachineExporter _exporter;
public B(IVirtualMachineExporter exporter)
{
_exporter = exporter;
}
private void ExportTask()
{
//Can this isAdhoc property be a property of IVirtualMachineExporter,
//or can the Request be a property? Will every implementation of the
//interface have a request?
//exporter.IsAdhoc = this.Request.isAdhoc;
_exporter.Prepare();
}
}
我没有你的设计细节。但是如果B将依赖于接口(IVirtualMachineExplorer
),那么它不应该知道或关心任何实现接口的类的任何内部细节。