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;
    }
}
但是,我得到以下编译错误:
错误的数组声明符:要声明托管数组,等级说明符在变量的标识符之前.要声明固定大小的缓冲区字段,请在字段类型之前使用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);
    }
}
重构到您的代码中:
private string[] myProperty;
public Indexer<string> MyProperty
{
    get
    {
        return myProperty.GetIndexer();
    }
}
这将允许您拥有任意数量的索引属性,而无需使用该IList<T>接口公开这些属性.