C#:公共方法{get{}set{}}问题
我不完全确定我的所有术语是否正确,所以如果我错了,请原谅我。我想知道是否可以向该方法发送参数。以下面为例。
public item (int index)
{
get { return list[index]; }
set { list[index] = value; }
}
我知道如果这样的话,它会出错。我要问的是是否有某种方法可以让它发挥作用。有什么建议或者我应该想办法解决它吗?
提前致谢。
I'm not entirely sure if I have all the terminology correct so forgive me if I'm wrong. I was wondering if it would be possible to send an argument(s) to the method. Take the following for example.
public item (int index)
{
get { return list[index]; }
set { list[index] = value; }
}
I know that as it is, it will error. What I'm asking is if there is some way to get it working. Any suggestions or should I figure out some way around it?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
试试这个:
这是 C# 的 索引器 语法,它有一些限制 (它不像 VB.NET 的参数化属性那么灵活),但它确实适用于您的特定示例。
Try this:
This is C#'s indexer syntax and it has some limitations (it's not as flexible as VB.NET's parameterful properties) but it does work for your specific example.
正如其他人所示,您可以将其变成索引器 - 顺便说一句,它可以有多个参数。
您不能做的是在C#中命名索引器...尽管您可以在VB中做到。因此,您不能有两个索引器,一个称为
Foo
,另一个称为Bar
...您需要编写返回值的属性,这些值本身是可索引的。说实话,有点痛苦:(As others have shown, you can turn it into an indexer - which can have multiple parameters, by the way.
What you can't do is name an indexer in C#... although you can in VB. So you can't have two indexers, one called
Foo
and the other calledBar
... you'd need to write properties which returned values which were themselves indexable. It's a bit of a pain, to be honest :(这称为索引器属性
This is called indexer property
我想您可能正在寻找的是:
I think what you might be looking for is:
作为记录,虽然其他答案是有效的,但您可能还需要考虑使用以下方法:
然后可以按如下方式使用:
其他答案将按以下稍有不同的方式使用:
您想要的答案取决于您到底想要实现什么目标,如果不查看其余代码就很难确定。
For the record, Whilst the other answers are valid, you might also want to consider using the following approach:
This could then be used as follows:
The other answers would be used in the following, slightly different, way:
The one you want depends on what exactly you are trying to achieve, which is difficult to determine without seeing the rest of the code.
除了现在已经多次提到的索引器之外,另一种可能性是使用索引器创建一个自定义类并将其实例作为属性返回。
例子:
Besides the indexer that has been mentioned several times now, another possibility is to make a custom class with an indexer and return an instance of it as a property.
Example:
您可以使用索引器来解决这个问题
You can use indexator for solving this problem