【发布时间】: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