【发布时间】:2010-07-27 14:24:51
【问题描述】:
在 C# 中,我发现 indexed properties 非常有用。例如:
var myObj = new MyClass();
myObj[42] = "hello";
Console.WriteLine(myObj[42]);
但是据我所知,没有语法糖来支持本身支持索引的字段(如果我错了,请纠正我)。例如:
var myObj = new MyClass();
myObj.field[42] = "hello";
Console.WriteLine(myObj.field[42]);
我需要这个的原因是我已经在我的类上使用了 index 属性,但是我有 GetNumX()、GetX() 和 SetX() 函数如下:
public int NumTargetSlots {
get { return _Maker.NumRefs; }
}
public ReferenceTarget GetTarget(int n) {
return ReferenceTarget.Create(_Maker.GetReference(n));
}
public void SetTarget(int n, ReferenceTarget rt) {
_Maker.ReplaceReference(n, rt._Target, true);
}
正如您可能看到的,将它们作为一个可索引的字段属性公开会更有意义。每次我想要语法糖时,我都可以编写一个自定义类来实现这一点,但所有样板代码似乎都是不必要的。
所以我编写了一个自定义类来封装样板文件,并使其易于创建可索引的属性。这样我可以按如下方式添加新属性:
public IndexedProperty<ReferenceTarget> TargetArray {
get {
return new IndexedProperty<int, ReferenceTarget>(
(int n) => GetTarget(n),
(int n, ReferenceTarget rt) => SetTarget(n, rt));
}
}
这个新的 IndexedProperty 类的代码如下所示:
public class IndexedProperty<IndexT, ValueT>
{
Action<IndexT, ValueT> setAction;
Func<IndexT, ValueT> getFunc;
public IndexedProperty(Func<IndexT, ValueT> getFunc, Action<IndexT, ValueT> setAction)
{
this.getFunc = getFunc;
this.setAction = setAction;
}
public ValueT this[IndexT i]
{
get {
return getFunc(i);
}
set {
setAction(i, value);
}
}
}
所以我的问题是:有没有更好的方法来完成所有这些操作?
具体来说,在 C# 中是否有更惯用的方法来创建可索引字段属性,如果没有,我该如何改进我的 IndexedProperty 类?
编辑:经过进一步研究,Jon Skeet 将此称为“named indexer”。
【问题讨论】:
-
请参阅github.com/dotnet/csharplang/issues/471 以获取添加此功能的请求以及支持和反对它的所有参数。直到今天,开发人员都拒绝添加它,因为他们没有看到该语言有足够的好处。
-
@OP 你的第一个链接不再有效
标签: c# properties indexed-properties