当前位置: 首页 > article >正文

windows C#-接口中的索引器

可以在接口上声明索引器。 接口索引器的访问器与类索引器的访问器有所不同,差异如下:

  • 接口访问器不使用修饰符。
  • 接口访问器通常没有正文。

访问器的用途是指示索引器为读写、只读还是只写。 可以为接口中定义的索引器提供实现,但这种情况非常少。 索引器通常定义 API 来访问数据字段,而数据字段无法在接口中定义。

下面是接口索引器访问器的示例:

public interface ISomeInterface
{
    //...

    // Indexer declaration:
    string this[int index]
    {
        get;
        set;
    }
}

索引器的签名必须不同于同一接口中声明的所有其他索引器的签名。

示例

下面的示例演示如何实现接口索引器。

// Indexer on an interface:
public interface IIndexInterface
{
    // Indexer declaration:
    int this[int index]
    {
        get;
        set;
    }
}

// Implementing the interface.
class IndexerClass : IIndexInterface
{
    private int[] arr = new int[100];
    public int this[int index]   // indexer declaration
    {
        // The arr object will throw IndexOutOfRange exception.
        get => arr[index];
        set => arr[index] = value;
    }
}
IndexerClass test = new IndexerClass();
System.Random rand = System.Random.Shared;
// Call the indexer to initialize its elements.
for (int i = 0; i < 10; i++)
{
    test[i] = rand.Next();
}
for (int i = 0; i < 10; i++)
{
    System.Console.WriteLine($"Element #{i} = {test[i]}");
}

/* Sample output:
    Element #0 = 360877544
    Element #1 = 327058047
    Element #2 = 1913480832
    Element #3 = 1519039937
    Element #4 = 601472233
    Element #5 = 323352310
    Element #6 = 1422639981
    Element #7 = 1797892494
    Element #8 = 875761049
    Element #9 = 393083859
*/

在前面的示例中,可通过使用接口成员的完全限定名来使用显示接口成员实现。 例如

string IIndexInterface.this[int index]
{
}

但仅当类采用相同的索引签名实现多个接口时,才需用到完全限定名称以避免歧义。 例如,如果 Employee 类正在实现接口 ICitizen 和接口 IEmployee,而这两个接口具有相同的索引签名,则需要用到显式接口成员实现。 即是说以下索引器声明:

string IEmployee.this[int index]
{
}

 在 IEmployee 接口中实现索引器,而以下声明:

string ICitizen.this[int index]
{
}

在 ICitizen 接口中实现索引器。 


http://www.kler.cn/a/472264.html

相关文章:

  • CSS——17. nth-child选择器2
  • 镜舟科技2024年度回顾,坚持长期价值,进一步实现商业突破
  • 数据挖掘——数据预处理
  • 安徽省乡镇界面图层+arcgis数据shp格式-乡镇名称和编码2020年+wgs84坐标内容测评
  • 解锁RDMA 技术:从原理到应用的深度剖析
  • 不停机从 PostgreSQL 迁移到 MySQL
  • (k8s)k8s系列之命令手册速查
  • 单片机软件定时器V4.0
  • nacos学习笔记(一)
  • php函数性能优化中应注意哪些问题
  • 深度学习知识点:RNN
  • [网络安全]BurpSuite爆破实战解题详析之BUUCTF Brute 1
  • 2025运维故障记 2 | 1/6 哪吒汽车官网无法正常访问
  • linux下的MongoDB手动安装部署详解
  • Perlin Noise算法
  • maven的pom.xml配置详解
  • 为什么ip属地一会河南一会江苏
  • Spring Boot项目中使用单一动态SQL方法可能带来的问题
  • 《Opencv》信用卡信息识别项目
  • 【NLP高频面题 - Transformer篇】Position encoding为什么选择相加而不是拼接呢?