2

我想在 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;
4

5 回答 5

7

您的语法不正确:

public Boolean this[Guid personGuid]
{
   get {
      Person person = GetPersonByGuid(personGuid);
      return person.IsSelected;
   }
   set {
      Person person = GetPersonByGuid(personGuid);
      person.IsSelected = value;
   }
}

索引器是使用this关键字声明的 - 您不能使用自己的名称。

使用索引器(C# 编程指南)

要在类或结构上声明索引器,请使用 this 关键字


此外,只能有一个接受类型的索引器 - 这是 C# 索引器语法的限制(可能是 IL 限制,不确定)。

于 2012-10-10T17:57:55.017 回答
5

索引器仅适用于this关键字。见这里

this 关键字用于定义索引器。

于 2012-10-10T17:57:13.433 回答
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; }

    ...
}
于 2012-10-10T18:03:45.950 回答
0

@Jojan在这里回答:

C# 3.0 规范

“索引器的重载允许类、结构或接口声明多个索引器,前提是它们的签名在该类、结构或接口中是唯一的。”

或者如果您的数据集很小,您可以使用 IList

public IList<Boolean> IsSelected
{
   get { ... }
}

public IList<Boolean> IsApproved
{
   get { .... }
}

或使用接口使用多个索引器技术

于 2012-10-10T18:25:50.730 回答
0

实际上,您可以有多个索引器接受类型。

但是,您不能有两个具有相同签名的索引器。相同的签名意味着参数编号和类型 - 所以上面的代码有两个具有相同签名的索引器。

如果代码更改为:

    Boolean this[string x, Guid personguid]

和 :

    Boolean this[Guid personguid]

它应该工作。

于 2013-10-18T14:53:21.023 回答