简体   繁体   中英

C# Generics Class with Interface Implementation Issue (Compiler Errors)

The generic type uses the interface and the interface uses the type. Is that the cause of this problem? The lines that emit compile errors are marked below. Is there a simple fix?

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;
        }

    }
}

When you declare the ParseListManager , you are putting a type constraint saying that the type which needs to be used as the generic type needs to have a parameterless constructor (the new() after the where keyword).

Also, it's a good idea not to use types which already exist when defining a generic type. Most code I've seen uses something like TOutput or a simple T .

Regarding the usage, it's a bit weird what you are trying to describe. What's the purpose of the Initialize method inside the interface? My interpretation would be something like: each object implementing IListType can be initialized with a ParseListManager

A solution would be to leave the Initialize method in the interface parameterless.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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