2013-05-22 30 views
-4

如何從類調用getter和setter到另一個類?我必須從Ball.c中調用另一個名爲StartGame.cs的類。我需要將它放入StartGame.cs中的計時器中。例如,在Ball類中。如何從類中調用getter和setter到另一個類中#

public class Ball 
{ 
    public int speedX { get; private set; } 
    public int speedY { get; private set; } 
    public int positionX { get; private set; } 
    public int positionY { get; private set; } 

    public Ball(int speedX, int speedY, int positionX, int positionY) 
    { 
     this.speedX = speedX; 
     this.speedY = speedY; 
     this.positionX = positionX; 
     this.positionY = positionY; 
    } 

    public int setSpeedX(int newSpeedX) 
    { 
     speedX = newSpeedX; 
     return newSpeedX; 
    } 

    public int setSpeedY(int newSpeedY) 
    { 
     speedY = newSpeedY; 
     return newSpeedY; 
    } 

    public int setPositionX(int newPositionX) 
    { 
     positionX = newPositionX; 
     return newPositionX; 
    } 

    public int setPositionY(int newPositionY) 
    { 
     positionY = newPositionY; 
     return newPositionY; 
    } 
} 

謝謝。

+0

究竟什麼是你的問題?也許通過例子來解釋它。 – JeffRSon

+0

這是不完全清楚你想要做什麼。你在一個'StartGame'的實例裏面,你有一個'Ball'的實例,並且想要設置那個實例的'speedX'屬性? – Corak

+0

我在StartGame.cs中有很多球。因此,我創建了一個名爲Ball.c的類。 Ball.cs創建方法。而且,我將使用Ball.cs在StartGame.cs中設置球的速度和位置。 – Guang

回答

1

如果您想在不同的類中使用變量,那麼必須將該變量定義爲public(或者如果您從另一個類繼承,則爲protected/protected internal)。

儘管暴露你的變量意味着暴露你的類的實現。最好是抽象出這些東西,並通過使用get和set訪問器的屬性公開變量。

0

如果您想從其他類在C#中調用變量然後就

Console.WriteLine(test.address); 

注意一兩件事,它應該是public

public class test 
{ 
    public static string address= ""; 
} 

下面是關於如何調用一個小說明,希望您根據自己的需要了解和修改。

0

我相當肯定,你要尋找的是這樣的:

class StartGame 
{ 
    void MyMethod() 
    { 
     Ball myBall = new Ball(0, 1, 2, 3); 

     int speedX = myBall.speedX;  // == 0 
     int speedY = myBall.speedY;  // == 1 
     int positionX = myBall.positionX; // == 2 
     int positionY = myBall.positionY; // == 3 
    } 
} 

因爲這些領域有私人setter方法,下面將是不可能的:

myBall.speedX = speedX; 

因爲setter不可訪問。
但是,你有公共setter方法:

myBall.setSpeedX(speedX); // this would work 

...
老實說,我很困惑...你複製粘貼從某處此代碼,只是不知道如何使用它?
我相當肯定,任何可以編寫這段代碼的人都不需要問這樣一個基本問題。如果我誤解了你的問題,我只會刪除這個答案。

+0

當我回答我的查詢時,我從一個用戶在stackoverflow中獲得了上述代碼。但是,我無法弄清楚如何使用它。 – Guang

0

你也可以把它寫成一個字段:

相關問題