[英]Named indexed property in C#?
一些語言 - 比如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#中輕松實現同樣的效果?
眾所周知的解決方案是創建一個代理類:
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
的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#的最簡單(就代碼長度和復雜性而言)的方式。 當然,除非有人發布更短更簡單的帖子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.