c# - 类中的奇怪属性

标签 c#

您能描述一下它的作用吗?我在一个项目中遇到过它,但不知道它是如何工作的。

public object this[int i]
{
    get { return columnValues[i]; }
}

最佳答案

这叫做indexer,用于索引,例如我们用它来从字符串中获取字符。你可以准备一下here , 或 here ,

string str = "heel";

char chr = str[0];

这是为类创建索引器的方式

class Sentence
{
    string[] words = "The quick brown fox".Split();
    public string this [int wordNum] // indexer
    {
       get { return words [wordNum]; }
       set { words [wordNum] = value; }
    }
}

Sentence s = new Sentence();
Console.WriteLine (s[3]); // fox
s[3] = "kangaroo";
Console.WriteLine (s[3]); // kangaroo

关于c# - 类中的奇怪属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12953898/

相关文章:

c# - LINQ to Entities - 在我的示例中排除部分发货订单的 WHERE 子句

c# - 动态更改 app.config 文件中的值

c# - 生成json时类型无效?

c# - 打印网页未显示一些图像和一些背景颜色 im 网页

c# - InvalidArgument= '0' 的值对于 'SelectedIndex' 无效。参数名称 : SelectedIndex

c# - Server.MapPath 给出了错误的路径,在 IIS 服务器上运行时不支持异常 "The given path' s 格式?

c# - Windows 服务中的 ODP.NET 数据库更改通知

c# - 仅将不同的 SQL 命令用于单元测试的最佳方法是什么?

c# - 系统.ArgumentNullException : Value cannot be null

c# - 在filter mvvm c# wpf的基础上自定义wpf折线图的x轴