簡體   English   中英

如何將接口與來自不同解決方案的類相關聯

[英]How to associate a Interface, with classes from different solutions

我有一個名為iChannels的接口,它只有一種方法。

using CHNL;
namespace iInterface
{
    public interface iChannels
    {
        string getData(string docXML);
    }
}

然后在另一個項目中,我有一個稱為Channel1的類,其定義如下:

using iInterface;
namespace CHNL
{
   public class Channel1:iChannels
   {
       string getData(string str)
       {
           return str;
       }
   }
}

我必須進行交叉引用,因為接口和類彼此了解。 之后,我有了一個網絡表單,我只想using iInterface;來使用using iInterface; ,但如果僅這樣做,就無法創建Channel1對象。

我的意圖是僅使用iInterface庫創建Channel1對象。

您不能從iInterface繼承,因為iInterface是名稱空間的名稱,而不是接口的名稱,因此,我認為您需要以下代碼;

using iInterface;
namespace CHNL
{
   public class Channel1 : iChannels
   {
       string getData(string str)
       {
           return str;
       }
   }
}

您的Web窗體不需要了解Channel1類,但是您的Web窗體所在的項目將需要引用Channel1所在的項目。

您可以使用類似的方法創建iChannels實例;

 iChannels myIChannels = new Channel1();

然后,您的Web表單可以引用iChannel,而無需知道iChannel的實際具體實現,在本例中為Channel1。

最好使用工廠注入或依賴注入來創建iChannel的實際實現,並避免使用“ new Channel1();”。 共。

我想我現在可以看到您的問題。

當您說“我的意圖是僅使用iInterface庫創建Channel1對象”時...這在C#中是不可能的,或者至少在沒有在與iChannels相同的庫中聲明Channel1的情況下,直接創建Channel1對象是不可能的。

您可以通過依賴項注入來實現。 概括地說,您的Web表單將依賴於iChannel,而依賴容器將提供它來實現iChannel(在您的情況下為Channel1)。

看一下這篇文章;

為什么要使用依賴注入?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM