C#中的命名索引属性?
一些语言(如Delphi)有一种非常方便的创建索引器的方法:不仅可以对整个类进行索引,甚至可以对单个属性进行索引,例如:C#中的命名索引属性?,c#,indexed-properties,C#,Indexed Properties,一些语言(如Delphi)有一种非常方便的创建索引器的方法:不仅可以对整个类进行索引,甚至可以对单个属性进行索引,例如: type TMyClass = class(TObject) protected function GetMyProp(index : integer) : string; procedure SetMyProp(index : integer; value : string); public property MyProp[index : integ
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;
}
}
}
优点:
- 没有代理类(它们占用内存空间,只用于单一目的,并且(在最简单的解决方案中)破坏封装
- 简单的解决方案,只需少量代码即可添加另一个索引属性
- 每个属性都需要不同的公共接口
- 随着索引属性的增加,类实现了越来越多的接口
这是将索引属性引入C#的最简单方法(就代码长度和复杂性而言)。当然,除非有人发布更短更简单的属性。可能重复@nawfal,我看不到解决方案中的接口?(这是知识共享问题,顺便说一句-答案也是我的)q是完全相同的,OP是以命名索引器命名的。你可以在该线程中提供答案。你可能在回答时没有看到原始的q,但是你看到了,然后添加另一个问题来仅仅回答是不合适的。顺便说一句,好的答案,+1(在一些相关的q中,这个答案也包括在内)@nawfal我相信,当你问一个名为“回答你的问题-以问答方式分享知识”的问题时,有一个特别的复选框。是的,但这是为非重复问题保留的。我的问题不在于你的答案(“知识”),但问题是。没什么大不了的。重复总是会发生。这取决于我们作为负责任的成员来进行清理。只是做我的一部分。显式实现的接口,没有想到这一点,很好!这非常干净。但是可以通过使用模板使它更干净:
public interface IIndexedProp{ValueT This[IndexT index]{get;}}
用法:公共类MyClass:IIndexedProp
而该类的其余部分是相同的。这样,您只需要一个接口-对于仅get/set道具可能需要更多接口。
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;
}
}
}