首页 > 解决方案 > 如何让一个类充当数组?

问题描述

带有索引器的类不是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
    }
}

标签: c#arrays

解决方案


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
    }
}

推荐阅读