c#界面FPGA实现 - 为什么会发生这种不建? [英] c# interface implemention - why does this not build?
问题描述
很抱歉,如果这已被问过,但它几乎是不可能的,以谷歌。我认为,一个int数组实现IEnumerable,因此东西应该能够实现IThing。为什么它不?
Sorry if this has been asked before but it's virtually impossible to google. I think that an int array implements IEnumerable and therefore Thing should be able to implement IThing. How come it doesn't?
public interface IThing
{
IEnumerable<int> Collection { get; }
}
public class Thing : IThing
{
public int[] Collection { get; set; }
}
注意,
public class Thing : IThing
{
public int[] Array { get; set; }
public IEnumerable<int> Collection
{
get
{
return this.Array;
}
}
}
是好的。
推荐答案
该接口的实现必须完全实现的接口。这prevents您返回实现该接口为成员的类型。
The interface implementation must implement the interface exactly. This prevents you from returning a type that implements that interface as the member.
如果你想做到这一点,一个选择是实现该接口的明确的:
If you wish to do this, one option is to implement the interface explicitly:
public interface IThing
{
IEnumerable<int> Collection { get; }
}
public class Thing : IThing
{
public int[] Collection { get; set; }
IEnumerable<int> IThing.Collection { get { return this.Collection; } }
}
这允许你对类使用的具体类型,但接口实现公共API来正确地履行。
This allows your public API for the class to use the concrete type, but the interface implementation to be fulfilled correctly.
例如,与上述情况,你可以这样写:
For example, with the above, you can write:
internal class Test
{
private static void Main(string[] args)
{
IThing thing = new Thing { Collection = new[] { 3, 4, 5 } };
foreach (var i in thing.Collection)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
这篇关于c#界面FPGA实现 - 为什么会发生这种不建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!