C# 它是否可用于传递引用类型(即)对象?
考虑以下示例,此处int i被传递为引用 我的问题是,我是否可以将引用类型传递给out?类似对象(即)静态空位和(外部示例oe) 下面的代码有一些错误C# 它是否可用于传递引用类型(即)对象?,c#,.net,pass-by-reference,out,ref,C#,.net,Pass By Reference,Out,Ref,考虑以下示例,此处int i被传递为引用 我的问题是,我是否可以将引用类型传递给out?类似对象(即)静态空位和(外部示例oe) 下面的代码有一些错误 class OutExample { int a; static void Sum(out OutExample oe) { oe.a = 5; } static void Main(String[] args) { int b; OutExample oe1=new OutExample
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();
}
}
是的
您必须在
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();
}
}
我建议你重新考虑一下。
引用类型是对存储位置的引用。传入
out
您正在传递对此引用的引用。你为什么不直接经过ref
?你试过了吗?它工作了吗?是的,我试过上面的代码,它工作得很好@MarcGravelya我尝试了上面的代码,它工作得很好@BenjaminDiele@Balaji所以您是否尝试过静态无效和(out OutExample oe)?发生了什么事?是的,但它显示出一些错误!在控件离开当前方法之前,必须将out参数“oe”指定给。如果它为空,我如何在Main()中使用它?@Balaji,这取决于Main
!当然,Sum
可以将其设置为非空实例。请完全编辑上述pgm和您的答案?好的,但b带红色下划线,表示正确,类不包含b的定义。这是正确的。您在Main
范围内定义了b
,因此它是局部变量,而不是像a
那样的类字段。b的定义仅在Main范围内,那么它怎么可能是非局部变量呢?它是局部变量,但仅在Main
方法的范围内,而不是整个类。我修改了示例Fantactive man,它工作得很好…我认为@Balaji正在使用out
,因为他想了解它是如何工作的。问题是这是一个好的做法还是一个坏的做法将在稍后出现:-)
static void Sum(out OutExample oe)
{
oe = null;
// or: oe = new OutExample();
}
class 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();
}
}