【问题标题】:Is it Out can be used for passing a reference type (i.e) Objects? [duplicate]它是否可以用于传递引用类型(即)对象? [复制]
【发布时间】:2015-02-17 03:33:35
【问题描述】:

考虑下面的例子,这里 int i 被传递以供参考。

我的问题是,我可以将引用类型传递给 out 吗?像对象(即)static void sum(out OutExample oe)

class OutExample
{
   static void Sum(out int i)
   {
      i = 5;
   }
   static void Main(String[] args)
   {
     int val;
     Sum(out val);
     Console.WriteLine(val);
     Console.Read();
   }
}   

现在下面的代码有一些错误,

class OutExample
{
  int a;
   static void Sum(out OutExample oe)
   {
    oe.a = 5;
   }
   static void Main(String[] args)
   {
    int b;
    OutExample oe1=new OutExample();
    Sum(out oe);
    oe.b=null;
    Console.WriteLine(oe.b);
    Console.Read();
   }
   }   

终于知道答案了!

class OutExample
{
int a;
int b;

static void Sum(out OutExample oe)
 {
   oe = new OutExample();
   oe.a = 5;
 }

static void Main(String[] args)
{ 
   OutExample oe = null; 
   Sum(out oe);
   oe.b = 10;
   Console.WriteLine(oe.a);
   Console.WriteLine(oe.b);
   Console.Read();
}
} 

【问题讨论】:

  • 你试过了吗?成功了吗?
  • 是的,我尝试了上面的代码,它运行良好。 @MarcGravell
  • 是的,我尝试了上面的代码,它运行良好。@BenjaminDiele
  • @Balaji 所以...你试过static void sum(out OutExample oe) 吗?发生了什么?
  • 是的,但它显示了一些错误!必须在控制离开当前方法之前分配 out 参数 'oe'

标签: c# .net pass-by-reference out ref


【解决方案1】:

您必须在Sum 方法中创建一个新的OutExample

class OutExample
{
   int a;
   int b;

   static void Sum(out OutExample oe)
   {
       oe = new OutExample();
       oe.a = 5;
   }

   static void Main(String[] args)
   { 
       OutExample oe = null; 
       Sum(out oe);
       oe.b = 10;
       Console.WriteLine(oe.a);
       Console.WriteLine(oe.b);
       Console.Read();
   }
} 

【讨论】:

  • 好的,但是 b 带有红色下划线表示,Class 不包含 b 的定义
  • 这是真的。您在Main 范围内定义了b,因此它是一个局部变量,而不是像a 这样的类字段。
  • b的定义只在Main里面,怎么可能是非局部变量呢?
  • 它是一个局部变量,但只在Main 方法的范围内,而不是整个类。我修改了例子
  • 了不起的人,它运作良好......
【解决方案2】:

是的……

static void Sum(out OutExample oe)
{
    oe = null;
    // or: oe = new OutExample();
}
class OutExample {}

【讨论】:

  • 如果它是 null 我如何在 Main() 中使用它?
  • @Balaji 最高可达Main!当然,Sum 可以将其设置为非空实例
  • 你能完整编辑上面的 pgm 和你的答案吗?
【解决方案3】:

我建议你重新考虑一些事情。 引用类型是对存储位置的引用。在out 中传递它是在传递对这个引用的引用。为什么不直接通过ref

【讨论】:

  • 我认为@Balaji 使用out 是因为他想了解它是如何工作的。是好是坏的问题将在稍后提出:-)
猜你喜欢
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 2011-12-05
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 2018-04-17
相关资源
最近更新 更多