的对象后,现实生活中的物体建模。例如,一个球具有半径,弹性,重量,颜色等。您还可以对球进行操作,例如投掷,滚动,放下,旋转等等。在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 = 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
请继续阅读教程,这是_extremely_基本的东西。 –
您也可以使用'var b = new Being();'; –
您必须在实例化之前声明对象的类型。例如'是b; b = new存在();'会起作用,但简单地使用'Being b = new Being();'更容易。 – Tim