gpt4 book ai didi

c# - C# 中的非整数索引索引器属性

转载 作者:行者123 更新时间:2023-11-30 19:02:24 25 4
gpt4 key购买 nike

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

最佳答案

您的语法不正确:

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) :

To declare an indexer on a class or struct, use the this keyword


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

关于c# - C# 中的非整数索引索引器属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12825378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com