如何将数据从一个类使用到另一个类中
本文关键字:一个 另一个 数据 | 更新日期: 2024-09-22 20:08:52
我在public abstract A : IVirtualMachineExporter
中有以下方法:
public override void Prepare() { ... }
我从另一个类B
:调用Prepare
public sealed class B
{
public new ExportJobRequest Request { get { return (ExportJobRequest)base.Request; } }
private void ExportTask()
{
IVirtualMachineExporter exporter = CreateExporter();
exporter.Prepare();
}
}
包含CCD_ 5的CCD_。我想在Prepare()
中使用此属性的信息。我该怎么做?我不想更改Prepare()
签名。
如何在不更改Prepare签名的情况下完成此操作?
好吧,不知何故Prepare
需要一个实例来调用isAdHoc
,所以如果你不想更改方法签名,你能更改class或接口吗?
类似于:
IVirtualMachineExporter exporter = CreateExporter(Request);
exporter.Prepare();
或
IVirtualMachineExporter exporter = CreateExporter();
exporter.Request = Request;
exporter.Prepare();
在类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方法,该方法可以通过其构造函数在新的exporter类上设置它。
看起来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
),那么它不应该知道或关心实现该接口的任何类的任何内部细节。