学习完几篇文章后,在他人文章基础上的加深学习。
**类和对象的内容来自:http://blog.itpub.net/12639172/viewspace-510130/ 重载内容来自:http://blog.youkuaiyun.com/wochuailimin/article/details/5629041**
类是具有相同的属性和功能的对象的抽象的集合,而类中的对象又具有不同的要素。举例来说:人类(类),而人类还分白人,黑人,黄种人(对象),不同种的人有不同的肤色(要素)。
我们需要先了解以下知识:
1. 常量的定义是使用const关键字,而且定义的同时必赋值。常量就是在程序中永远不能改变的数据,且必须通过类的名字进行引用。
2. 实例化类对象的基本语法为:
ClassName bjName = new ClassName([参数]);
类的名字 对象名
3. 静态static方法不能通过对象来引用,必须通过类来引用。
4. 方法重载(程序末尾有解释)。
下面用代码实例来深入理解:
using System;
using System.Collections.Generic;
using System.Text;
namespace testsharp
{
//定义一个类[人类],人类的标实符记作Human
class Human
{
public const string country = "China";
public string skincolor = "";
public string sex = "";
public void HumanFunction(string country)
{
switch(skincolor)
{
case"yellow":
Console.WriteLine("Maybe he is from China.");
break;
case "white":
Console.WriteLine("Maybe he is from America.");
break;
case "black":
Console.WriteLine("Maybe he from is Egypt.");
break;
default:
Console.WriteLine("Sorry.");
break;
}
}
public static void HumanFunction()
{
Console.WriteLine("Don't konw where he came from.");
}
}
class Program
{
//Main 方法是程序的入口点,所以无论这个program类放在哪里,程序都会从Main方法开始执行。
static void Main(string[] args)
{
//我们来创建一个Human类的实例化对象Carl
Human Carl = new Human();
//我们来定义一个string类型的变量Carlcountry,接受国籍,并且把它打印出来。
string Carlcounty=Human.country;
Console.WriteLine("Carl's country is "+Carlcountry);
//我们来给Carl定义一个性别,因为sex是Human类里的public字段,所以在Human类的外部可以访问,所以用 对象名. 来引用sex。
Carl.sex="man";
Carl.skincolor="blue";
Console.WriteLine("Skincolor is{0},sex is{1}",Carl.skincolor,Carl.sex);
//很明显,我们发现blue并不是人的肤色。我们可以通过以下方法弥补,也就是当我们输入blue后,将肤色作为参数带入到HumanFunction方法中进行判断,在输出肤色。
Carl.HumanFunction(Carl.skincolor);
Carl.skincolor="yellow";
Console.WriteLine("Skincolor is {0},sex is {1}",Carl.skincolor,Carl.sex);
Carl.HumanFunction(Carl.skincolor);
Human.HumanFunction();
}
}
}
首先解释一下什么是方法重载:
方法重载是指在同一个类中方法同名,参数不同,调用时根据实参的形式,选择与它匹配的
方法执行操作的一种技术。
这里所说的参数不同是指以下几种情况:
1.参数的类型不同
2.参数的个数不同
3.参数的个数相同时,他们的先后顺序不同。
注意:系统会认为是同一个方法的两种情况:
1.返回类型不同,方法名和参数个数、顺序、类型都相同的两个方法
2.返回类型不同、方法名和参数的个数、顺序、类型都相同的两个方法,但是参数的名字不同
以上两种情况会导致系统报错。