参数接受错误的类型仍然运行正常 - 为什么?

Cla*_*ung 4 c# parameters methods

下面我有一个从互联网上搜索的方法,用C#计算Excel的百分比函数.我修改了一下以适合我的程序,但没有改变主要逻辑.

该程序编译并运行正常,没有任何错误(我知道).无论如何进一步检查我的代码,在我的主要部分,我使用函数调用

        double result = percentRank( array, x); 
Run Code Online (Sandbox Code Playgroud)

哪里

x是一个int
数组是一个List(int)

它与指定的percentRank方法的类型不同,但它仍然运行良好.我的问题是为什么?

        private static double percentRank(List<int> array, double x)
        {
            //        Calculate the PERCENTRANK(array, x)
            //If X matches one of the values in the array, this function is
            //equivalent to the Excel formula =(RANK(x)-1)/(N-1) where N is the number of data points.
            //If X does not match one of the values, then the PERCENTRANK function interpolates.
            // http://www.pcreview.co.uk/forums/algorithm-computing-excel-percentrank-t946312.html


            array.Sort();

            double result = 0;
            bool foundX = false;

            for (int index = 0; index < array.Count; index++)
            {
                if (array[index] == x)
                {
                    result = ((double)index) / ((double)array.Count - 1);
                    foundX = true;
                    break;
                }
            }
            // calculate value using linear interpolation

            if (foundX == false)
            {
                double x1, x2, y1, y2;

                x1 = x2 = x;

                for (int i = 0; i < array.Count - 1; i++)
                {
                    if (array[i] < x && x < array[i + 1])
                    {
                        x1 = array[i];
                        x2 = array[i + 1];
                        foundX = true;
                        break;
                    }
                }

                if (foundX == true)
                {
                    y1 = percentRank(array, x1);
                    y2 = percentRank(array, x2);

                    result = (((x2 - x) * y1 + (x - x1) * y2)) / (x2 - x1);
                }
                else
                {
                    // use the smallest or largest value in the set which ever is closer to valueX

                    if (array[0] > x)
                    {
                        result = 0;
                    }
                    else
                    {
                        result = 1;
                    }
                }
            }

            return result;
        }
Run Code Online (Sandbox Code Playgroud)

编辑:好的答案是隐式类型转换.我可以禁用吗?我不喜欢它,因为它可能会产生一些我不知道的错误.

Ree*_*sey 11

我的问题是为什么?

您可以将整数分配给double值.C#将隐式转换Int32Double.

你可以在这里看到:

double value = 3;
Run Code Online (Sandbox Code Playgroud)

由于相同的隐式转换,因此允许这样做.没有这种转换,你必须输入:

double value = 3.0;
Run Code Online (Sandbox Code Playgroud)

这在C#语言规范的"6.1.2隐式数字转换"部分中指定.

隐式数字转换是:

...

  • 从int到long,float,double或decimal.