繁体   English   中英

C# Generics Class 接口实现问题(编译器错误)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM