首页 > 解决方案 > 具有接口实现问题的 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;
        }

    }
}

标签: c#generics

解决方案


当您声明 时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;
    }
}

推荐阅读