如何在c#中从一个类调用getter和setter到另一个类

本文关键字:调用 一个 getter 另一个 setter | 更新日期: 2023-09-27 18:14:42

如何从一个类调用getter和setter到另一个类?我需要从ball。cs中调用另一个类startgame。cs。我需要把它放在startgame。cs中的计时器中。例如,在类Ball.

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

谢谢。

如何在c#中从一个类调用getter和setter到另一个类

如果你想在另一个类中使用一个变量,那么这个变量必须定义为public(或者如果你从另一个类继承,则必须定义为protected/protected internal)。

但是,像那样公开变量意味着公开类的实现。最好将这些内容抽象出来,并使用get和set访问器通过属性公开变量。

如果你想在c#中从其他类调用变量,只需

Console.WriteLine(test.address);

注意一点,它应该是public,如

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

这里有一个关于如何打电话的小说明,希望您理解并根据您的需要修改

我很确定,你要找的东西是这样的:

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

由于这些字段有私有设置符,因此不可能执行以下操作:

myBall.speedX = speedX;

因为setter不可访问。
但是,您确实有公共setter方法:

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

…老实说,我很困惑……您是否从某处复制粘贴了这段代码,只是不知道如何使用它?
我相当肯定,任何能编写这段代码的人都不需要问这样一个基本问题。如果我误解了你的问题,我就删掉这个答案。

也可以写成一个字段:

private String somevar;
public String Somevar{
 get{ return this.somevar}
 set { this.somevar = value}
}