在 C# 中使用索引器从结构中获取值

using indexers in c# to get values from struct

我定义了一个结构如下:

using System;
using System.Collections.Generic;
public struct PacketPenetration
{    
    private Dictionary<double, double[,]> penetration;
    public PacketPenetration(Dictionary<double, double[,]> penetration)
    {        
        this.penetration = penetration;
    }

    public Dictionary<double, double[,]> Penetration { get { return penetration; } }

    public double this[double index1, int index2, int index3]
    {
        get
        {
            return this.penetration[index1][index2,index3];
        }
    }
}

并像这样实例化:

var penetration = new PacketPenetration();

我的目标是能够将项目添加到 penetration 并能够使用结构中定义的索引器从中获取值。但是下面的代码行不起作用:

penetration.Add(3.5, testArray);

testArray 是一个 double[,] 问题出在哪里?

它不起作用,因为您的 PacketPenetration 没有方法 Add

您的索引器配置为只获取,而且拥有索引器不会使 class 奇迹般地实现方法 Add

如何向 PacketPenetration 添加一个 Add 方法:

    public void Add(double index , double[,] array)
    {
        penetration.Add(index, array);
    }

如果你真的需要通过索引器,你可以添加以下内容:

    public double[,] this[double index1, double [,] array]
    {
        set
        {
            this.penetration[index1] = value;
        }
    }

然后:

  penetration[3.5] =  testArray;

你首先要做两件事:

  1. var penetration = new PacketPenetration(); ==> var penetration = new PacketPenetration(initializedDictionary); 调用无参构造函数不会初始化穿透字典。因此 NullReferenceException
  2. penetration.Add(3.5, testArray); ==> penetration.Penetration.Add(3.5, testArray); 或者为 struct
  3. 定义 Add 方法