【问题标题】:Use of unassigned out parameter 'q' [duplicate]使用未分配的输出参数“q”[重复]
【发布时间】:2018-06-10 21:46:49
【问题描述】:

使用未分配的参数“q”和“g”时出错,请纠正我做错的地方。提前致谢。

using System;  
using System.Collections.Generic;
using System.Linq;
using System.Text;  
using System.Threading.Tasks;   

class Program  
{  
    static void Main(string[] args)  
    {  
        int p = 23;  
        int f = 24;  
        Fun(out p, out f);  
        Console.WriteLine("{0} {1}", p, f);  

    }  
    static void Fun(out int q, out int g)  
    {  
        q = q+1;  
        g = g+1;  
    }  
}  

【问题讨论】:

  • 听起来你需要去阅读out 的文档。你似乎不明白它的作用。

标签: c# unassigned-variable


【解决方案1】:

你做错的正是编译器你做错的——你试图在它确定之前从out参数读取分配的。看看你的代码:

static void Fun(out int q, out int g)  
{  
    q = q + 1;  
    g = g + 1;  
}  

在每种情况下,赋值表达式的右侧都使用了一个 out 参数,并且该 out 参数还没有被赋予一个值。 out参数最初不是绝对赋值的,必须在方法返回前确定赋值(通过异常除外)

如果想法是增加两个参数,您应该改用ref

static void Fun(ref int q, ref int g)  
{  
    q = q + 1;  
    g = g + 1;  
}  

或者更简单地说:

static void Fun(ref int q, ref int g)  
{  
    q++;
    g++;
}  

您需要将调用代码更改为:

Fun(ref p, ref f);

【讨论】:

  • 意思是我不能用out参数吗?
  • @Maddy:在方法中分配参数之前,你不能做任何需要参数值的事情,不。请记住,您可以写 int p, f; Fun(out p, out f); - 在这种情况下您会期望值是什么?
  • 与我从您的方法中得到的答案相同,但是我试图通过 help op OUT 参数得到它...
  • @Maddy:为什么?您正在尝试将out 参数用于它们明确不是为它们设计的东西......它们被称为out 因为数据通过它们out,而不是in .
  • 嗯...现在我明白了...谢谢...!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多