我希望在C#中有一个索引属性:
public Boolean IsSelected[Guid personGuid]
{
get {
Person person = GetPersonByGuid(personGuid);
return person.IsSelected;
}
set {
Person person = GetPersonByGuid(personGuid);
person.IsSelected = value;
}
}
public Boolean IsApproved[Guid personGuid]
{
get {
Person person = GetPersonByGuid(personGuid);
return person.IsApproved;
}
set {
Person person = GetPersonByGuid(personGuid);
person.IsApproved= value;
}
}
Visual Studio抱怨非整数索引器语法:
我知道.NET supports non-Integer indexors。
我会写另一种语言:
private
function GetIsSelected(ApproverGUID: TGUID): Boolean;
procedure SetIsSelected(ApproverGUID: TGUID; Value: Boolean);
function GetIsApproved(ApproverGUID: TGUID): Boolean;
procedure SetIsApproved(ApproverGUID: TGUID; Value: Boolean);
public
property IsSelected[ApproverGuid: TGUID]:Boolean read GetIsSelected write SetIsSelected;
property IsApproved[ApproverGuid: TGUID]:Boolean read GetIsApproved write SetIsApproved;
end;
答案 0 :(得分:7)
您的语法不正确:
public Boolean this[Guid personGuid]
{
get {
Person person = GetPersonByGuid(personGuid);
return person.IsSelected;
}
set {
Person person = GetPersonByGuid(personGuid);
person.IsSelected = value;
}
}
使用this
关键字声明索引器 - 您无法使用自己的名称。
来自Using Indexers (C# Programming Guide):
要在类或结构上声明索引器,请使用this关键字
此外,只能有一个接受类型的索引器 - 这是C#的索引器语法的限制(可能是IL限制,不确定)。
答案 1 :(得分:5)
索引器仅适用于this
关键字。请参阅here。
this关键字用于定义索引器。
答案 2 :(得分:1)
就像Matt Burland和Oded所说,索引器只能使用这个关键字,所以你需要一个带有你需要的接口的代理类:
public class PersonSelector
{
private MyClass owner;
public PersonSelector(MyClass owner)
{
this.owner = owner;
}
public bool this[Guid personGuid]
{
get {
Person person = owner.GetPersonByGuid(personGuid);
return person.IsSelected;
}
set {
Person person = owner.GetPersonByGuid(personGuid);
person.IsSelected = value;
}
}
}
public class MyClass
{
public MyClass()
{
this.IsSelected = new PersonSelector(this);
}
public PersonSelector IsSelected { get; private set; }
...
}
答案 3 :(得分:0)
@Jojan回答here:
C#3.0规范
“索引器的重载允许类,结构或接口 声明多个索引器,前提是它们的签名是唯一 类,结构或接口。“
或者如果您的数据集很小,您可以使用IList
public IList<Boolean> IsSelected
{
get { ... }
}
public IList<Boolean> IsApproved
{
get { .... }
}
答案 4 :(得分:0)
实际上,您可以让多个索引器接受类型。
但是,您不能拥有两个具有相同签名的索引器。相同的签名表示参数编号和类型 - 因此上面的代码有两个具有相同签名的索引器。
如果代码更改为:
Boolean this[string x, Guid personguid]
和:
Boolean this[Guid personguid]
它应该有用。