namespace ConsoleApplication3
{
class Class1
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _type;
public string Type
{
get { return _type; }//取值
set { _type = value; }//赋值
}
private string _food;
public string Food
{
get { return _food; }
set {
if (value=="meat")
{
_food = "我吃肉!";
}
else
{
_food = "我不吃别的!";
}
}
}
}
}
namespace ConsoleApplication3
{
class Class2//function 重载
{
public void function(string s)
{
Console.WriteLine(s);
}
public void function(string s,string s1)
{
Console.WriteLine(s+s1);
}
}
}
namespace ConsoleApplication3
{
class Class3
{
/// <summary>
/// 构造函数,每一个类至少有一个构造函数(class a = new class()),函数名字与类名相同,并且没有返回值,下面的public不写也可以默认存在,构造函数也可以重载
/// </summary>
public void class4()//不是构造函数,是新的方法
{
}
public Class3()//默认的构造函数
{
}
public Class3(int a)//带参数的构造函数数
{
Num1 = a;
}
public int Num1;
public static int Num2;//静态成员,不随着NEW造对象走
}
}
namespace ConsoleApplication3
{
class Class4
{
public Class4(string sname,string ssex,int sold)
{
name = sname;
sex = ssex;
old = sold;
}
public string name;
public string sex;
public int old;
}
}
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Class1 s = new Class1();
s.Food = "meat";
s.Name = "tiger";
s.Type = "less";
Console.WriteLine(s.Food);//以上为封装
Class2 data = new Class2();
data.function("123");
data.function("aaa"+"123");//函数重载
Class3 data1 = new Class3();
data1.Num1 = data1.Num1 + 3;//data1点不出Num2
Class3.Num2 += 3;//不通过data1,直接通过Class调用
Class3 data2 = new Class3();
data2.Num1 = data1.Num1 + 3;
Class3.Num2 += 3;//静态成员Num2不随着造的对象走,Num2为3,3+3=6
Console.WriteLine(Class3.Num2);//为6
Console.WriteLine(data2.Num1);
Console.WriteLine(data1.Num1);
Class3 data4 = new Class3();//构造函数的重载
Class3 data3 = new Class3(2);//构造函数的重载有参数的
Console.WriteLine(data3.Num1);//构造函数结果为2,为某些成员变量赋初始值
Class4 t1 = new Class4("张三", "男", 18);//用构造函数给变量赋初始值
Class4 t2 = new Class4("李四", "女", 17);
Console.WriteLine(t1.name+t1.old+t1.sex);
Console.ReadLine();
}
}
}