![](/img/trans.png)
[英]Force calling the derived class implementation within a generic function in C#?
[英]C# generic Interface implementation to derived class
我被困在通用類和接口的實現中。 我不確定我想做的事情是否可行。
這是我的代碼:- 我定義了一個泛型類,它的類型不像
public class Response<T>
{
public T Data { get; set; }
public Response()
{
Data = default(T);
}
}
和一個現在只有一個功能的接口
public interface IOInterface<T> where T : Response<T>
{
Response<T> ReadAdvantechChannel(Dictionary<string, string> IOParameters);
}
一個將實現此接口的派生類:-
public class AdvantechOperation : IOInterface<T>
{
public Response<AIRecordInfo> ReadAdvantechChannel(Dictionary<string, string> IOParameters)
{
Response<AIRecordInfo> resp = new Response<AIRecordInfo>();
}
}
和 AIrecordinfo 再次上課
public class AIRecordInfo
{
double[] ArryMaxValueAIdouble;
double[] ArryMinValueAIdouble;
double[] ArryAVGValueAIdouble;
}
我想要做的是實現一個實現定義接口但返回接口函數類型的類對於我未來的派生類不清楚,這就是為什么我使它成為通用的並嘗試實現它我現在的類“AdvantechOperation”。 我的界面將具有三個函數,並且所有函數返回類型將彼此不同,這就是為什么我將其設為通用返回類型 Response 並在我目前的類 AdvantechOperation 中,將 T 替換為 AIRecordInfo。 但是我在編譯這個項目時遇到了下面的錯誤
錯誤 7 類型“T”不能用作泛型類型或方法“IOModule.IOInterface”中的類型參數“T”。 沒有從“T”到“IOModule.Response”的裝箱轉換或類型參數轉換。 D:\\MTS\\SMS\\DAQAdvantechdll\\DAQAdvantechdll\\IOCommunication.cs 28 18 IOModule 錯誤 8 'IOModule.AdvantechOperation' 沒有實現接口成員 'IOModule.IOInterface.ReadAdvantechChannel(System.Collections.Generic.Dictionary)'。 'IOModule.AdvantechOperation.ReadAdvantechChannel(System.Collections.Generic.Dictionary)' 不能實現 'IOModule.IOInterface.ReadAdvantechChannel(System.Collections.Generic.Dictionary)',因為它沒有匹配的返回類型 'IOModule.Response'。 D:\\MTS\\SMS\\DAQAdvantechdll\\DAQAdvantechdll\\IOCommunication.cs 28 18 IOModule
擺脫接口的泛型類型約束,並在實現接口時使用AIRecordInfo
作為泛型類型參數:
public class AdvantechOperation : IOInterface<AIRecordInfo>
{ ... }
在我看來,你想要這個:
public class Response<T> { }
public interface IOInterface<T> where T : Response<T>
{
T ReadAdvantechChannel(Dictionary<string, string> IOParameters);
}
public class AdvantechOperation : IOInterface<AIRecordInfo>
{
public AIRecordInfo ReadAdvantechChannel(Dictionary<string, string> IOParameters)
{
return new AIRecordInfo();
}
}
public class AIRecordInfo : Response<AIRecordInfo>
{
double[] ArryMaxValueAIdouble;
double[] ArryMinValueAIdouble;
double[] ArryAVGValueAIdouble;
}
Response<T>
不再需要主體,因為IOInterface<T>
的方法只返回T
,它必須從Response<T>
繼承。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.