我一直在尝试几种不同的方法,但我得出的结论是无法做到。这是我过去从其他语言中喜欢的语言功能。这只是我应该注销的东西吗?
Kilhoffer
问问题
8522 次
3 回答
60
不,C# 不支持静态索引器。然而,与其他答案不同,我看到拥有它们很容易。考虑:
Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)
Encoding y = Encoding["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")
我怀疑它会相对很少使用,但我认为它被禁止很奇怪——据我所知,它没有特别的原因造成不对称。
于 2008-09-30T19:18:52.563 回答
16
您可以使用静态索引属性模拟静态索引器:
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")
于 2010-08-18T09:04:38.753 回答
0
不,但是可以创建一个静态字段来保存使用索引器的类的实例...
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; }
}
}
}
}
...Which could be accessed in the way you are intending. This can be tested in the Immediate Window...
Memory.Register[0] = 12 * 12;
?Memory.Register[0]
144
于 2016-02-14T21:57:36.343 回答