Reputation: 63
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;
}
}
}
Upvotes: 0
Views: 55
Reputation: 65
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;
}
}
Upvotes: 1