繁体   English   中英

c#将参数值从函数传递到其他函数

[英]c# passing Parameters values from function to other function

有什么办法可以从“ functionone”中的Parameters中获取值并在“ functionTwo”中对其进行计算,而无需再次编写那是一小段代码,例如我的意思

public void functionone(int x, int y)
{

   x = 1;
   y = 2;

}

public void functiontwo(int a , int b )
{
   a=x+y;
   b=x-y;

   Console.WriteLine(a);
   Console.WriteLine(b);


}

您错误地实现了functionone,我猜是这样:public void functionone(int x,int y){x = 1; y = 2; }通常不是传递参数并在方法中更改其值的方法,或者换句话说,x和y应该保留您作为参数传递的值,并且不会在方法内部分配。

定义一个全局x和全局y,那么您可以在该范围内的任何位置访问它。

例:

class Abc{
    int globalX;
    int globalY;
....
public void functionone(int x, int y)
{
   globalX = 1 + x;
   globalY = 2 + y;
}

public void functiontwo(int a , int b )
{
   a=globalX + globalY;
   b=globalX - globalY;

   Console.WriteLine(a);
   Console.WriteLine(b);
}

}

为了解释我的评论

int globalX;
int globalY;

public void functionone(ref int x, ref int y)
{
    x = 1;
    y = 2;
}

public void functiontwo(ref int a , ref int b)
{
    a = globalX + globalY;
    b = globalX - globalY;

    Console.WriteLine(a);
    Console.WriteLine(b);
}


// in main

functionone(ref globalX, ref globalY);
// globalX and globalY are now 1 and 2

functiontwo(ref a, ref b);
// a = 3 and b = -1  ->  'globalX +/- globalY'

这样,您可以设置传递给functiononefunctiontwo的任何变量的值。

但是,它看起来并不好,我认为这不是一个好的代码。 您的概念似乎有误,因此也许您可以发布遇到的问题的描述?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM