ArgumentOutOfRangeException

时间:2017-04-17 22:01:17

标签: c#

我已经开始在C#上做一个项目,它有对象(类CLA)。 CLA创建一个集合(列表)。

我会在List<Cla>上运行,需要HighValueLowValue等等。但ArgumentOutOfRangeException进入了这里。

我可以在构造函数中调用方法吗?这段代码是否正确?

class Program
{
    static void Main(string[] args)
    {
        List<Cla> ClaList = new List<Cla>();
        ClaList.Add(new Cla("a", 10.3, "Priznak1", 1));
        ClaList.Add(new Cla("b", 3.3, "Priznak1", 1));
        ClaList.Add(new Cla("c", 7.3, "Priznak1", 1));
        ClaList.Add(new Cla("d", 9.3, "Priznak1", 1));
        ClaList.Add(new Cla("e", 8.3, "Priznak1", 1));

        CritListSmall NewTest = new CritListSmall(ClaList);
        Console.WriteLine("ddd {0}", NewTest.HighValue);
    }
}


class CritListSmall
{
    public double HighValue;
    public double LowValue;

    public CritListSmall(List<Cla> p)
    {
        HighValue = p[0].ObjectValue;
        LowValue = p[0].ObjectValue;

        int NumberElements;

        NumberElements = p.Count;
        for (int i = 1; i <= NumberElements; i++)
        {
            double m = p[i].ObjectValue; //Exception occurs here
            if (HighValue < m)
                HighValue = m;
        }
        for (int l = 1; l <= NumberElements; l++)
        {
            double n = p[l].ObjectValue; //and here
            if (LowValue > n)
                LowValue = n;
        }
    }


    public class Cla
    {
        public string ObjectName;
        public double ObjectValue;
        public string PriznakName;
        public int ClassNumber;

        public Cla(string on, double ov, string pn, int cn)
        {
            ObjectName = on;
            ObjectValue = ov;
            PriznakName = pn;
            ClassNumber = cn;
        }

        public double CritValue;
        public double ExpValue;

        public bool Outlier;
        public double AbsoluteValue;
    }
}

3 个答案:

答案 0 :(得分:2)

在C#集合中有从零开始的索引。这意味着如果列表中有5个项目,它们的索引将为0,1,2,3,4。而不是

for(int i = 1; i <= NumberElements; i++)

你应该使用

for(int i = 0; i < NumberElements; i++)
            ^    ^
     from zero   and less than count of items

答案 1 :(得分:1)

在C#数组索引中,从0开始,而不是1,因此您需要将循环更改为:

for (int i = 0; i < NumberElements; i++)

for (int l = 0; l < NumberElements; l++)

答案 2 :(得分:0)

 for(int i = 1; i <= NumberElements; i++)

这是你的问题。必须是:

for(int i = 0; i < NumberElements; i++)

for(int l = 0; l < NumberElements; l++)

为什么呢? NumberElements是p的计数,例如10.但索引是0到9。