我将结构定义如下:
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[,],问题在哪里?
发布于 2017-03-29 14:52:51
因为您的PacketPenetration没有Add方法,所以它无法工作。
您的索引器配置为get-only,而且,拥有索引器并不会使类奇迹般地实现方法Add。
将Add方法添加到PacketPenetration中如何:
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;发布于 2017-03-29 15:01:13
你首先有两件事要做:
var penetration = new PacketPenetration(); ==> var penetration = new PacketPenetration(initializedDictionary);调用无参数构造函数将不会初始化渗透字典。因此NullReferenceExceptionpenetration.Add(3.5, testArray); ==> penetration.Penetration.Add(3.5, testArray);或为结构定义Add方法https://stackoverflow.com/questions/43096838
复制相似问题