我正在做一些统计工作,并且想要重构以下方法:
public static blah(float[] array)
{
//Do something over array, sum it for example.
}
但是,我不想使用 float[],而是想使用某种索引可枚举(例如,对非常大的数组使用从磁盘动态加载) )。
我创建了一个简单的界面,并想使用它。
public interface IArray<T> : IEnumerable<T>
{
T this[int j] { get; set; }
int Length { get; }
}
我的问题是:
- float[] 只继承 IList,而不继承 IArray,而且据我所知,没有办法改变它。
- 我想放弃 IArray 并只使用 IList,但我的类需要实现许多方法,例如
Add
、RemoveAt
尽管它们是固定大小
- 然后我的问题:如何float[] 可以实现 IList 而它没有这些方法吗?
欢迎任何帮助。
干杯
I'm doing some work with stats, and want to refactor the following method :
public static blah(float[] array)
{
//Do something over array, sum it for example.
}
However, instead of using float[] I'd like to be using some kind of indexed enumerable (to use dynamic loading from disk for very large arrays for example).
I had created a simple interface, and wanted to use it.
public interface IArray<T> : IEnumerable<T>
{
T this[int j] { get; set; }
int Length { get; }
}
My problem is :
- float[] only inherits IList, not IArray, and AFAIK there's no way to change that.
- I'd like to ditch IArray and only use IList, but my classes would need to implement many methods like
Add
, RemoveAt
although they are fixed size
- And then my question : how can float[] implement IList whereas it doesn't have these methods ?
Any help is welcome.
Cheers
发布评论
评论(3)
事实上,
float[] array
确实实现了IList
:这是根据19.6:
In fact,
float[] array
does implementIList<float>
:This is per 19.6:
我最终写了以下内容:
公共类 IArrayWrapper :IArray
{
私有浮点数[]innerArray;
我对此并不感到自豪,但我认为隐式运算符应该可以解决我的问题......希望如此。
I ended up writing the following stuff :
public class IArrayWrapper : IArray
{
private float[] innerArray;
I'm not very proud of it, but I think implicit operators should solve my problem... hopefully.
Array of T 还实现了
IList
等(但这些并不总是在工具中显示,Array 的几个方面在运行时有特殊情况)。这是事实,但这样的实现速度相当快(如果您只需要非修改操作,您可以从修改方法中抛出
NotImplementedException
)。实际上只需几分钟即可完成,并且您的实现应该是可重用的。还有像
ReadOnlyCollection
这样的类型可以帮助避免大量此类工作。类型可以显式实现接口方法。它们不是类型的直接成员,但转换到接口(或反射)将允许访问。这允许类型化集合实现
IEnumerator.Current
(返回Object
),同时还提供返回正确类型的Current
属性。Array of T also implements
IList<T>
and others (but these don't always show in tools, several aspects of Array as special cased by the runtime).This is true, but such implementation is quite quick to do (and should you only need non-modifying operations, you can just throw a
NotImplementedException
from modifying methods).In practice in only takes a few minutes to do, and your implementation should be reusable. Also there are types like
ReadOnlyCollection<T>
to help avoid a lot of this work.A type can explicitly implement interface methods. They are not directly members of the type, but casting to the interface (or reflection) will allow access. This allows a typed collection to implement
IEnumerator.Current
(returningObject
) while also providing aCurrent
property that returns the correct type.