gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:02:30 26 4
gpt4 key购买 nike

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

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

return myProperty[idx];
}
set
{
myProperty[idx] = value;
}
}

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

Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.

最佳答案

这个怎么样:写一个只做一件事和一件事的类:提供对一些底层索引集合的元素的随机访问。给这个类(class)一个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> 公开这些属性界面。

关于c# - 在 C# 中公开数组元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3547739/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com