最近遇到个关于接口的奇怪的问题

接口的作用众所周知了,而且C#的接口,必须明确两点:

1.必须实现接口中定义的方法、属性等,原型必须一样(返回值类型、函数名,参数类型)

2.实现接口的类中必须使用public修饰符

那我们下面来看一个例子:

var array = new string[10];

foreach (var tp in array.GetType().GetInterfaces())
{
    Console.WriteLine(tp.Name);
}

 

上面的例子取出了对象array实现的所有接口名称,我们看到有下面这些:

 

ICloneable
IList
ICollection
IEnumerable
IList`
1
ICollection`
1
IEnumerable`
1


我们看到array实现了ICollection接口,我们跳到这个接口代码区看下:

[ComVisible(true)]
public interface ICollection : IEnumerable
{
    
int Count get; }
    
bool IsSynchronized { get; }
    
object SyncRoot { get; }
    
void CopyTo(Array array, int index);
}

 

我们发现上面有个Count属性,这个……我们都知道string[]类型的对象是不会有Count属性的,只会有Length属性。

这样的话,其实已经违背了上面列的两条了。而且我发现在NHibernate里面也有一个这样的类,实现了IEnumerable接口,却没有提供IEnumerator GetEnumerator()的实现。

这就是我百思不得其解的地方。查了些资料,没找到合理解释,希望谁能来解释一下!

posted @ 2009-03-19 01:37  CoderZh  阅读(1144)  评论(6编辑  收藏  举报