在C#中公开数组元素的属性

Pau*_*els 13 c# arrays properties

我想在C#中创建一个属性,用于设置或返回数组的单个成员.目前,我有这个:

private string[] myProperty;
public string MyProperty[int idx]
{
    get
    {
        if (myProperty == null)
            myProperty = new String[2];

        return myProperty[idx];
    }
    set
    {
        myProperty[idx] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我得到以下编译错误:

错误的数组声明符:要声明托管数组,等级说明符在变量的标识符之前.要声明固定大小的缓冲区字段,请在字段类型之前使用fixed关键字.

Dan*_*Tao 14

怎么样:编写一个只做一件事和一件事的类:提供对某些底层索引集合元素的随机访问.给这个类一个this索引器.

对于要提供随机访问的属性,只需返回此索引器类的实例.

琐碎的实施:

public class Indexer<T>
{
    private IList<T> _source;

    public Indexer(IList<T> source)
    {
        _source = source;
    }

    public T this[int index]
    {
        get { return _source[index]; }
        set { _source[index] = value; }
    }
}

public static class IndexHelper
{
    public static Indexer<T> GetIndexer<T>(this IList<T> indexedCollection)
    {
        // could cache this result for a performance improvement,
        // if appropriate
        return new Indexer<T>(indexedCollection);
    }
}
Run Code Online (Sandbox Code Playgroud)

重构到您的代码中:

private string[] myProperty;
public Indexer<string> MyProperty
{
    get
    {
        return myProperty.GetIndexer();
    }
}
Run Code Online (Sandbox Code Playgroud)

这将允许您拥有任意数量的索引属性,而无需使用该IList<T>接口公开这些属性.


lep*_*pie 5

您必须使用this索引器的属性名称.


joe*_*ote 5

C#每个类只允许一个索引属性,因此您不得不使用它.