c# - 具有接口实现问题的 C# 泛型类(编译器错误)
问题描述
泛型类型使用接口,接口使用类型。这是这个问题的原因吗?下面标记了发出编译错误的行。有简单的解决方法吗?
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
,您放置了一个类型约束,说明需要用作泛型类型的类型需要有一个无参数构造函数( 关键字new()
之后)。where
此外,在定义泛型类型时最好不要使用已经存在的类型。我见过的大多数代码都使用类似TOutput
或简单的T
.
关于用法,您要描述的内容有点奇怪。接口内部的方法的目的是什么Initialize
?我的解释是这样的:每个实现的对象IListType
都可以用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;
}
}
推荐阅读
- python - 从 YouTube、SoundCloud 和其他平台获取元数据和 MRL
- java - 方法标记为 @Async 在 Map 对象操作处停止执行 Spring boot
- node.js - 为什么sequelize在我进行查询时尝试选择额外的列
- docker - Samba Share .pid 权限问题
- django - 在 Django 中的所有视图上添加消息
- css - LESS 将 css 颜色标签转换为列表/变量中的十六进制代码
- triggers - 创建审计触发器错误没有足够的值
- jquery - 我是如何在新的动态 html 中使用 jquery 验证的?
- javascript - 如何将整页博客添加到博客预览?
- primevue - PrimeVue TabView 活动标签样式