学习字段与属性是学习C#面向对象编程的开始,由于没有C++等面向对象编程语言的基础,所以理解面向对象编程花了些时间,不过这都不是问题。
关于面向对象:
关于类与对象的区别: 类,是一种事物,比如说“咖啡”是一个类,而类中的一个特定东西,如“雀巢拿铁” 便是一个对象。
所以,我写的第一个类也和咖啡有关。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class cafe
{
//定义字段
private string brand;
private string kind;
//定义属性
public string Brand
{
get { return brand; } //可读
set { brand= value; } //可写
}
public string Kind
{
get { return kind; }
set { kind = value; }
}
//获取咖啡信息的方法
public string Getcafe()
{
string info = string.Format("咖啡品牌:{0} 咖啡种类:{1}", brand, kind);
return info; //返回info
}
}
}
主程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
cafe obj = new cafe();
Console.WriteLine("请输入咖啡品牌:");
obj.Brand =Console.ReadLine();
Console.WriteLine("请输入咖啡种类");
obj.Kind =Console.ReadLine();
Console.WriteLine(obj.Getcafe());
Console.ReadKey();
}
}
}
万物皆对象,这是OOP的基本理念。