簡體   English   中英

c# 接口、依賴倒置和泛型類型

[英]c# Interfaces, Dependency Inversion and Generic Types

我一直在與這個斗爭一段時間。 我有一個 API 來檢索 JSON 格式的數據源:

數據源:

[
 {
        "name": "Datasource 1",
        "tags": "Ds1",
        "product": 1,
        "status": 1,
        "Type": 2,
        "datasource": {
            "testurl1" : "",
            "testurl2: : ""
        }

},
 {
        "name": "Datasource 2",
        "tags": "Ds2",
        "product": 2,
        "status": 1,
        "Type": 2,
        "datasource": {
            "string1" : "",
            "string2: : ""
        }

}
]

數據源具有相同的外部屬性。 但是,數據源屬性會有所不同。 數據源屬性將由它自己的一組屬性組成,這些屬性因數據源而異。

我創建了一個要在不同項目中使用的接口:

public Interface IGeneral
{
   void SetTestData(TestDataModel testData);
}

但是您會看到 TestDataModel 類型是具體類型。 我已經嘗試了一種策略模式並創建了一個具有通用數據源屬性的 BaseDatasource 類,但我不確定最好的前進方式。

基本上,我想檢索一個數據源,將其綁定到必要的 POCO 模型,實例化一個實現 IGeneral 接口的類,然后調用該類的 SetTestData 方法並傳入數據源對象,而不是它是具體類型。 在 SetTestData 方法中,我會有類似這樣的代碼:

示例 1:

public class MyClass1 : IGeneral
{
     public void SetTestData(TestDataModel testData)
        {
            testData.product = 1;
            testData.datasource.testurl1 = "sasasas";
        }
}

示例 2:

public class MyClass2 : IGeneral
{
     public void SetTestData(TestDataModel testData)
        {
            testData.product = 2;
            testData.datasource.string1 = "dsds";
        }
}

這是否符合要求:

class DataSourceBase
{
}
class DataSource1 : DataSourceBase
{
}

class TestDataPerMarket<TDataSource> where TDataSource : DataSourceBase
{
    public int product {get;set;}
    public TDataSource datasource {get;set;}
}

public Interface IGeneral
{
    void SetTestData<TDM<TDS>>(TDM<TDS> testData) 
        where TDM : class, 
        where TDS : DataSourceBase;
}

(ps 我還沒試過編譯這個!)

暫無
暫無

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

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