c# - 如何让一个类充当数组?
问题描述
带有索引器的类不是System.Array
. 但我想像数组一样使用我的实现。例如访问扩展方法。
有没有办法做到这一点?
public class MyArray<T>
{
private T[] _array;
public MyArray(int size)
{
_array = new T[size];
}
public T this[int index]
{
get { return _array[index]; }
set { _array[index] = value; }
}
}
public static class ArrayExtensions
{
public static void T[] Foo(this T[] array)
{
// ..
}
}
public class ArrayUser
{
public ArrayUser()
{
var a = new MyArray(10);
a.Foo(); // does not compile, Foo() is unknown
}
}
解决方案
MyArray 使用泛型,因此您的扩展方法也需要使用泛型。
public class MyArray<T>
{
private T[] _array;
public MyArray(int size)
{
_array = new T[size];
}
public T this[int index]
{
get { return _array[index]; }
set { _array[index] = value; }
}
}
public static class ArrayExtensions
{
public static void Foo<T>(this MyArray<T> myArray)
{
// ..
}
}
public class ArrayUser
{
public ArrayUser()
{
var a = new MyArray<int>(10);
a.Foo(); // does not compile, Foo() is unknown
}
}
推荐阅读
- c++ - 我需要对齐的内存存储来加载文件吗?
- arrays - 从文件夹中的图像创建一个数组并随机呈现给定数量的图像(Objective-C)
- javascript - 如何在基于 Django Intranet Web 的应用程序中读取客户端 Windows 用户名?
- python - 错误:总数 使用 Stacking ensemble 进行分类模型时的迭代次数达到极限
- performance - Jmeter 脚本在 100 个用户之前工作正常,并从 150 个用户开始抛出“Socket Exception Error : Connection Closed”
- php - 无法访问 laravel 对象属性
- json - Angular html,如何对嵌套对象进行 ngfor 循环?
- botframework - 在 Microsoft 应用清单中添加“机器人”条目:“找到没有类型名称的值”
- java - 我在 addPointLoad() 方法中遇到空指针异常
- javascript - 在 React js 中获取客户端本地时区