[英]C# Generics Class with Interface Implementation Issue (Compiler Errors)
泛型類型使用接口,接口使用類型。 這是這個問題的原因嗎? 下面標記了發出編譯錯誤的行。 有簡單的解決方法嗎?
using System;
using System.Collections.Generic;
namespace CcelBookParse.Utility
{
public interface IListType
{
void Initialize(ParseListManager<IListType> value); // Error.
}
public class ParseListManager<IListType> : List<IListType> where IListType : new()
{
private int NextIndex;
public ParseListManager() { }
protected void Initialize()
{
NextIndex = 0;
}
protected IListType GetNext()
{
IListType Result;
if (Count < NextIndex)
{
Result = this[NextIndex];
Result.Initialize(this); // Error.
}
else if (Count == NextIndex)
{
Result = new IListType();
Add(Result);
}
else
{
throw new Exception("List allocation index error.");
}
return Result;
}
}
}
當您聲明ParseListManager
時,您正在放置一個類型約束,說明需要用作泛型類型的類型需要有一個無參數構造函數(在where
關鍵字之后的new()
)。
此外,在定義泛型類型時最好不要使用已經存在的類型。 我見過的大多數代碼都使用TOutput
或簡單的T
之類的東西。
關於用法,您要描述的內容有點奇怪。 接口內部的Initialize
方法的目的是什么? 我的解釋是這樣的:每個實現IListType
的 object 都可以用ParseListManager
初始化
一種解決方案是將接口中的Initialize
方法保留為無參數。
public interface IListType
{
void Initialize();
}
public class ParseListManager<TList> : List<TList> where TList : IListType, new()
{
private int NextIndex;
public ParseListManager() { }
protected void Initialize()
{
NextIndex = 0;
}
protected TList GetNext()
{
TList Result;
if (Count < NextIndex)
{
Result = this[NextIndex];
Result.Initialize();
}
else if (Count == NextIndex)
{
Result = new TList(); // You cannot instantiate an interface, you need a proper implementation
Add(Result);
}
else
{
throw new Exception("List allocation index error.");
}
return Result;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.