C# 中的对象是根据现实生活中的对象建模的。例如,球具有半径、弹力、重量、颜色等。您还可以对球执行动作,例如投掷、滚动、掉落、旋转等。在 C# 中,您可以为球:
public class Ball
{
// Radius in inches
public double Radius { get; set; }
public double Bounciness { get; set; }
// Weight in lbs
public double Weight { get; set; }
public string Color { get; set; }
// more properties
// constructor - this is called when your class is instantiated (created)
public Ball()
{
}
// throw the ball
public void Throw()
{
// method for throwing ball
}
// roll the ball
public void Roll()
{
// method for rolling ball
}
// drop the ball
public void Drop()
{
// method for dropping ball
}
// spin the ball
public void Spin()
{
// method for spinning the ball
}
// more methods for interacting with a ball
}
然后你会声明一个 Ball 的实例,设置属性和调用方法,如下所示:
Ball ball = new Ball();
ball.Color = "Red";
ball.Weight = 1.2; // 1.2 lbs
ball.Radius = 12; // 12 inches
ball.Bounciness = 0.2; // for use in a physics engine perhaps
ball.Throw(); // throw the ball
ball.Drop(); // drop the ball
// etc