前言
瞭解了面向對象和麪向過程,明確了類與對象的概念,那麼在C#中類與對象的聲明與定義具體是怎樣的?
繼續看一看
類的聲明
類中可以包括但並不一定需要全部包括字段、屬性和方法
字段是用來讓編程人員定義對象的特徵,屬於內部數據,一般只讓其在類內部訪問,而屬性則是對字段進行保護,使外部成員訪問,並且可限定其取值和賦值,方法則與之前的一致。
public class Fruits
{
//字段,默認訪問權限爲private
string _name;
public string Name
{
get {return _name;}
set {_name=value;}
}
double _price;
//屬性--特殊之處
//屬性的作用就是保護字段,對字段的取值和賦值進行限定
//屬性的本質就是兩個方法
public double Price //用以控制Price的取值範圍
{
get {return _price;}//控制賦值
set {
if(value<0||value>100)
{
value = 0;
}
_price=value;}//控制取值
}
string _color;
public string Color
{
get {return _color;}
set {_color=value;}
}
double _weight;
public double Weight //用以控制Price的取值範圍
{
get {return _weight;}//控制賦值
set {
if(value<0||value>100)
{
value = 0;
}
_weight=value;}//控制取值
}
//方法
static void Import()
{
Console.WriteLine("{0}的價格爲{1},顏色是{2},重{3}g",this.Name,this.Price,this.Color,this.Weight);
}
}
創建對象
對象需要在main函數中創建纔有效果,對象的創建如下所示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01面向對象
{
class Program
{
static void Main(string[] args)
{
/*
* {public} class 類名
{
字段;
屬性;
方法(函數);
}
*/
//創建Fruits類的對象
Fruits /*自定義類*/ apple = new Fruits();
//屬性的作用:限定對象的定義值
apple.Name = "蘋果";
apple.Price = 3.42;
apple.Color = "紅";
apple.Weight=102.3;
apple.Import();
Console.ReadKey();
}
}
}