的對象後,現實生活中的物體建模。例如,一個球具有半徑,彈性,重量,顏色等。您還可以對球進行操作,例如投擲,滾動,放下,旋轉等等。在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