使用 GetEnumerator 进行字典初始化 C#

Using GetEnumerator for Dictionary initialization C#

我有一个 class Cluster.cs 定义为:

public class Cluster
{
        protected int _clusterID = -1;
        private static int _clusterCount = 0;

        protected int _attributeCount;
        // _clusterObjects contains EvoObjects in this cluster. 
        protected List<EvoObject> _clusterObjects = new List<EvoObject>();

        /** _nkA[_i] is the total occurrences of the attribute _i in this cluster*/
        protected Int32[] _nkA;

        // For each attribute, record their values as KeyValuePair.

        protected Dictionary<Int32, UtilCS.KeyCountMap<Int32>> _attributeValues = new Dictionary<Int32, UtilCS.KeyCountMap<Int32>>();

        public Cluster(int _clusterID, int _attributeCount)
        {
            this._clusterID = _clusterID;
            this._attributeCount = _attributeCount;
            _nkA = new Int32[_attributeCount];
        }

        // Initialize _attributeValues
        IEnumerable<Int32>  _range = Enumerable.Range(0, _attributeCount).GetEnumerator(_i => {_attributeValues[_i] = new UtilCS.KeyCountMap<Int32>()});
}  

初始化 _attributeValues 时,出现错误:

"No overloaded method for GetEnumerator takes 1 argument"

而我只有 1 个参数要初始化,即 _attributeValues 这实际上是一个字典,这就是为什么必须枚举它的原因。

此外,如果我声明 _attributeCount 静态,我将无法在构造函数中使用它,如果我声明它是非静态的,我将无法使用它的 Range Enumerable 方法。

那我该如何初始化_attributeValues
如何声明_attributeCount静态或非静态?

Enumerable.Range(0, _attributeCount).ToList().ForEach(x => _attributeValues.Add(x, new UtilCS.KeyCountMap<Int32>()));

您似乎在尝试使用在创建对象时设置的变量 (_range) 来初始化字典。这应该移到构造函数中。您似乎正在尝试使用键 0、1、2 和值 new UtilCS.KeyCountMap().

创建三个新属性

如果这是正确的,那么我建议使用它作为构造函数。

public Cluster(int _clusterID, int _attributeCount)
{
  this._clusterID = _clusterID;
  this._attributeCount = _attributeCount;
  _nkA = new Int32[_attributeCount];

  for (var i = 0; i < 3; i++)
  {
    _attributeValues.Add(i, new UtilCS.KeyCountMap<int>());
  }
}

但是,由于您发送的是 _attributeCount,所以我认为您可以使用它来代替 3。

public Cluster(int _clusterID, int _attributeCount)
{
  this._clusterID = _clusterID;
  this._attributeCount = _attributeCount;
  _nkA = new Int32[_attributeCount];

  for (var i = 0; i < _attributeCount; i++)
  {
    _attributeValues.Add(i, new UtilCS.KeyCountMap<int>());
  }
}