您可能知道,C#中的数组实现IList<T>了其他接口.但不知何故,他们这样做没有公开实现Count属性IList<T>!数组只有一个Length属性.
这是一个明显的例子,C#/ .NET打破了自己关于接口实现的规则,还是我错过了什么?
我总是被告知在数组中添加元素的方式如下:
创建数组+ 1element的空副本,然后将原始数组中的数据复制到其中,然后加载新元素的新数据
如果这是真的,那么由于内存和CPU利用率的原因,在需要大量元素活动的场景中使用数组是正确的,对吗?
如果是这种情况,你是否应该尽量避免在添加大量元素时尽可能多地使用数组?你应该使用iStringMap吗?如果是这样,如果您需要两个以上的维度并且需要添加大量元素添加,会发生什么.你刚刚受到性能打击还是应该使用其他东西?
在下面的代码示例调用l.Add(s)和c.Add(s)成功,但对于一般的,当它失败IList<string>.
var l = new List<string>();
dynamic s = "s";
l.Add(s);
var c = (ICollection<string>)l;
c.Add(s);
var i = (IList<string>)l;
i.Add("s"); // works
i.Add(s); // fails
Run Code Online (Sandbox Code Playgroud)
https://dotnetfiddle.net/Xll2If
未处理的异常:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:方法'Add'的重载在System.Dynamic.Uynamic.UpdateDelegates.UpdateAndExecuteVoid2 [T0,T1]的CallSite.Target(Closure,CallSite,IList`1,Object)中取'1'参数](CallSite网站,T0 arg0,T1 arg1)位于C:\ Dev\PlayGround\PlayGround\Program.cs中的Program.Main():第13行
IList<T>来源于ICollection<T>.有人可以解释为什么呼叫IList.Add失败?
一个类型数组同时实现System.Collections.IList和System.Collections.Generic.ICollection<T>接口,都有自己的IsReadOnly特性.但到底是怎么回事?
var array = new int[10];
Console.WriteLine(array.IsReadOnly); // prints "False"
var list = (System.Collections.IList)array;
Console.WriteLine(list.IsReadOnly); // prints "False"
var collection = (System.Collections.Generic.ICollection<int>)array;
Console.WriteLine(collection.IsReadOnly); // prints "True"
Run Code Online (Sandbox Code Playgroud)
该IList阵列的视图表现为我预计,返回相同的阵列本身,但是ICollection<T>该阵列的视图返回true.
这种行为有没有合理的解释,还是编译器/ CLR错误?(如果是后者,我会感到非常惊讶,因为你会想象之前会发现这种情况,但这是违反直觉的,我无法想到解释可能是什么......).
我正在使用C#3.0/.NET 3.5 SP1.