仅仅是为了我的好奇心,
如果我有
ICollection<string> collection = new List<string>();
然后我想“集合”只能访问在ICollection接口或其祖先接口中声明的那些属性。这就是OOP所说的。
但实际上我们可以访问List的所有属性。为什么呢?
希望我在这里不要问一些愚蠢的问题。我的假设是错误的。
编辑:让我试试我想说的话
public interface myInterface {
public void InterfaceMethod();
}
public class MyClass : myInterface
{
public MyClass()
{
}
public void InterfaceMethod()
{
Console.WriteLine("InterfaceMethod called");
}
public void AnotherMethod() {
Console.WriteLine("AnotherMethod called");
}
}
public class Program
{
private static IContainer Container { get; set; }
static void Main(string[] args)
{
myInterface myObject = new MyClass();
myObject.InterfaceMethod();
myObject.AnotherMethod(); //Now myObject is not aware of AnotherMethod, which is correct
}
}
答案 0 :(得分:0)
ICollection<string>
继承自IEnumerable<string>
,也许您会混淆两者共享的属性,因为List<string>
也继承自IEnumerable<string>
ICollection<T> : IEnumerable<T>,IEnumerable
和
List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable