2016-08-28 71 views
0

有沒有什麼辦法讓從參數值「functionone」,並在「functiontwo」計算的話不寫一遍這對例如我的意思了一小段代碼C#傳遞參數值

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


} 
+0

不行,你必須顯式調用它。 – zerkms

+0

不,你應該從functionOne調用functiontwo並傳遞參數。 –

+0

@NeerajSharma我怎麼稱呼它? – shar

回答

0

要實現functionone錯誤我想 這樣做: 公共無效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); 
} 

} 
+0

注意:您可以使用'ref'關鍵字來傳遞變量,所以在方法調用後保留該值。 'functionone'應該讓變量爲它們設置1和2,你傳遞的是x的值,而不是變量。 – rsqLVo

0

解釋我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' 

這樣你可以設置你傳遞給functiononefunctiontwo任何變量的值。

但是它看起來並不好,在我看來,這不是一個好的代碼。你的概念看起來不對,所以也許你可以發表你遇到的問題的描述?