List<T> to IEnumerable<T> problem in interface
namespace WpfApplication3
{
public class Hex
{
public String terr;
}
public class HexC : Hex
{
int Cfield;
}
public interface IHexGrid
{
IE开发者_开发技巧numerable<Hex> hexs { get; }
}
public class hexGrid : IHexGrid //error CS0738: 'WpfApplication3.hexGrid' does not
{
public List<Hex> hexs { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<HexC> hexList1 = new List<HexC>();
genmethod(hexList1); //but this compiles fine
}
void genmethod(IEnumerable<Hex> hexList)
{
string str1;
foreach (Hex hex in hexList)
str1 = hex.terr;
}
}
}
The full error message is: 'WpfApplication3.hexGrid' does not implement interface member 'WpfApplication3.IHexGrid.hexs'. 'WpfApplication3.hexGrid.hexs' cannot implement 'WpfApplication3.IHexGrid.hexs' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable'.
Why doesn't List implicitly cast to IEnumerable above? Thanks in advance!
That kind of casting (covariance?) doesn't apply to class/interface declarations. It can only be done on parameters and return types.
The compiler is looking for the exact signature, isn't finding it, and rightly saying you didn't implement the member. The property/method signature must match exactly.
This answer actually sums it up better than I could explain.
Christopher has the right answer, but you could easily work around this by having a private property be the actual list and then the getter on the hexGrid just return the casted IEnumerable interface from the List.
public class hexGrid : IHexGrid
{
private List<Hex> _hexs { get; set; }
public IEnumerable<Hex> hexs
{
get { return _hexs as IEnumerable; }
set { _hexs = new List<Hex>( value ); }
}
}
精彩评论