简体   繁体   English

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

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

are there any way to get the values from Parameters in "functionone" and calculate it in the "functiontwo" without writing that again that's a small code for example what i mean 有什么办法可以从“ 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);


}

You are implementing functionone wrongly I guess doing this: public void functionone(int x, int y) { x = 1; 您错误地实现了functionone,我猜是这样:public void functionone(int x,int y){x = 1; y = 2; y = 2; } is normally not the way to pass parameters and change its values in the method, or saying in another way, x and y should be holding the values you pass as parameters, and no getting assigned inside the method.. }通常不是传递参数并在方法中更改其值的方法,或者换句话说,x和y应该保留您作为参数传递的值,并且不会在方法内部分配。

define a global x and global y, then you can access to it everywhere in that scope.. 定义一个全局x和全局y,那么您可以在该范围内的任何位置访问它。

Example: 例:

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);
}

}

To explain my comment : 为了解释我的评论

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'

This way you can set the values of any variables you pass to functionone or functiontwo . 这样,您可以设置传递给functiononefunctiontwo的任何变量的值。

However it doesn't look good and in my opinion it's not a good code. 但是,它看起来并不好,我认为这不是一个好的代码。 Your concept seems wrong, so maybe you can post a description of the problem you encountered? 您的概念似乎有误,因此也许您可以发布遇到的问题的描述?

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

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