一些语言 - 比如Delphi - 有一种非常方便的方法来创建索引器:不仅是整个类,甚至单个属性都可以编入索引,例如:
type TMyClass = class(TObject)
protected
function GetMyProp(index : integer) : string;
procedure SetMyProp(index : integer; value : string);
public
property MyProp[index : integer] : string read GetMyProp write SetMyProp;
end;
这可以很容易地使用:
var c : TMyClass;
begin
c = TMyClass.Create;
c.MyProp[5] := 'Ala ma kota';
c.Free;
end;
有没有办法在C#中轻松实现相同的效果?
答案 0 :(得分:9)
众所周知的解决方案是创建一个代理类:
public class MyClass
{
public class MyPropProxy
{
private MyClass c;
// ctor etc.
public string this[int index]
{
get
{
return c.list[index];
}
set
{
c.list[index] = value;
}
}
}
private List<string> list;
private MyPropProxy myPropProxy;
// ctor etc.
public MyPropProxy MyProp
{
get
{
return myPropProxy;
}
}
}
但是(除了这实际上解决了这个问题),这个解决方案大多只引入缺点:
MyPropProxy
&#39; s ctor,什么需要更多的代码。 public interface IMyProp
{
string this[int index] { get; }
}
public class MyClass : IMyProp
{
private List<string> list;
string IMyProp.this[int index]
{
get
{
return list[index];
}
set
{
list[index] = value;
}
}
// ctor etc.
public IMyProp MyProp
{
get
{
return this;
}
}
}
优点:
缺点:
这是将索引属性引入C#的最简单(就代码长度和复杂性而言)的方式。当然,除非有人发布更短更简单的内容。