Use of unassigned out parameter, c#

后端 未结 4 629
借酒劲吻你
借酒劲吻你 2020-12-29 01:06

I have very simple problem. I made a very simple function for you to demonstrate my problem.

static void Main(string[] args)       
{
    double[,] mydouble          


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 01:58

    If the array is defined OUTSIDE of the function, you should use a ref (or nothing, considering the array is a reference type). out means the parameter will be initialized in the function before it returns. Some examples of use:

    static void Main(string[] args)
    {
        double[,] mydouble;
        mynewMatrix(out mydouble);// call of method
    
        double[,] mydouble2 = new double[1, 4];
        mynewMatrix2(mydouble2);// call of method
    
        // useless for what you want to do
        mynewMatrix3(ref mydouble2);// call of method
    }
    
    public static void mynewMatrix(out double[,] d)
    {
        d = new double[1, 4];
    
        for (int i = 0; i < 4; i++)
        {
            d[0, i] = i;
        }
    }
    
    public static void mynewMatrix2(double[,] d)
    {
        for (int i = 0; i < 4; i++)
        {
            d[0, i] = i;
        }
    }
    
    // useless for what you want to do
    public static void mynewMatrix3(ref double[,] d)
    {
        for (int i = 0; i < 4; i++)
        {
            d[0, i] = i;
        }
    }
    

    I'll add that if you don't know what is the difference between ref and out you could read Difference between ref and out parameters in .NET

提交回复
热议问题