题
这个问题在这里已经有答案了:
- 静态索引器? 7 个答案
我一直在尝试几种不同的方法,但我得出的结论是这是不可能的。这是我过去从其他语言中喜欢的一个语言功能。这只是我应该注销的事情吗?
解决方案
不,C# 不支持静态索引器。然而,与其他答案不同的是,我发现拥有它们很容易有意义。考虑:
Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)
Encoding y = Encoding["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")
我怀疑它相对很少被使用,但我认为它被禁止很奇怪 - 据我所知,它没有任何特殊原因导致不对称。
其他提示
您可以使用静态索引属性来模拟静态索引器:
public class MyEncoding
{
public sealed class EncodingIndexer
{
public Encoding this[string name]
{
get { return Encoding.GetEncoding(name); }
}
public Encoding this[int codepage]
{
get { return Encoding.GetEncoding(codepage); }
}
}
private static EncodingIndexer StaticIndexer;
public static EncodingIndexer Items
{
get { return StaticIndexer ?? (StaticIndexer = new EncodingIndexer()); }
}
}
用法:
Encoding x = MyEncoding.Items[28591]; // Equivalent to Encoding.GetEncoding(28591)
Encoding y = MyEncoding.Items["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")
不,但是可以创建一个静态字段来保存使用索引器的类的实例...
namespace MyExample {
public class Memory {
public static readonly MemoryRegister Register = new MemoryRegister();
public class MemoryRegister {
private int[] _values = new int[100];
public int this[int index] {
get { return _values[index]; }
set { _values[index] = value; }
}
}
}
}
...可以按照您想要的方式访问。这可以在立即窗口中进行测试...
Memory.Register[0] = 12 * 12;
?Memory.Register[0]
144
不隶属于 StackOverflow