[英]Non-integer indexed Indexer properties in C#
我想在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支持非整数索引器 。
在另一种语言中,我会写:
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;
你的语法不正确:
public Boolean this[Guid personGuid]
{
get {
Person person = GetPersonByGuid(personGuid);
return person.IsSelected;
}
set {
Person person = GetPersonByGuid(personGuid);
person.IsSelected = value;
}
}
使用this
关键字声明索引器 - 您不能使用自己的名称。
要在类或结构上声明索引器,请使用this关键字
另外,只有一个索引器可以接受一个类型 - 这是C#索引器语法的限制(可能是IL限制,不确定)。
索引器仅适用于this
关键字。 看到这里 。
this关键字用于定义索引器。
就像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; }
...
}
@Jojan 在这里回答:
C#3.0规范
“重载索引器允许类,结构或接口声明多个索引器,前提是它们的签名在该类,结构或接口中是唯一的 。”
或者如果您的数据集很小,您可以IList
public IList<Boolean> IsSelected
{
get { ... }
}
public IList<Boolean> IsApproved
{
get { .... }
}
实际上,您可以让多个索引器接受类型。
但是,您不能拥有两个具有相同签名的索引器。 相同的签名意味着参数编号和类型 - 因此上面的代码有两个具有相同签名的索引器。
如果代码更改为:
Boolean this[string x, Guid personguid]
并且:
Boolean this[Guid personguid]
它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.