How to use data from one class into another?

时间:2016-04-15 15:12:27

标签: c# oop design-patterns

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.

3 个答案:

答案 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,而IVirtualMachineExporterA)的实施取决于RequestB不应该对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),那么它不应该知道或关心任何实现接口的类的任何内部细节。