4e1548abe2
Part1
78 lines
2.1 KiB
C#
78 lines
2.1 KiB
C#
namespace Lesson3_封装_成员方法
|
|
{
|
|
#region 知识点一 成员方法声明
|
|
//基本概念
|
|
//1.声明在类语句块中
|
|
//2.是用来描述对象的行为的
|
|
//3.规则和函数声明规则相同
|
|
//4.收到访问修饰符规则影响
|
|
//5.返回值参数不做限制
|
|
//6.方法数量不做限制
|
|
|
|
//注意:
|
|
//1.成员方法不要加static关键字
|
|
//2.成员方法 必须实例化出对象 再通过对象来使用 详单与该对象执行了某个行为
|
|
//3.成员方法 收到访问修饰符限制
|
|
|
|
class Person
|
|
{
|
|
public string name;
|
|
public int age;
|
|
|
|
public void Speak(string str)
|
|
{
|
|
Console.WriteLine("{0}说{1}",name,str);
|
|
}
|
|
|
|
public bool IsAdult()
|
|
{
|
|
return age >= 18;
|
|
}
|
|
public Person[] friend;
|
|
/// <summary>
|
|
/// 加朋友的方法
|
|
/// </summary>
|
|
/// <param name="p">p是传入的新朋友</param>
|
|
public void AddFriend(Person p)
|
|
{
|
|
if (friend == null)
|
|
{
|
|
friend = new Person[] { p };
|
|
}
|
|
else
|
|
{
|
|
Person[] temp = new Person[friend.Length];
|
|
for (int i = 0; i < friend.Length; i++)
|
|
{
|
|
temp[i] = friend[i];
|
|
}
|
|
temp[temp.Length -1] = p;
|
|
friend = temp;
|
|
}
|
|
}
|
|
}
|
|
#endregion
|
|
internal class Program
|
|
{
|
|
static void Main(string[] args)
|
|
{
|
|
Console.WriteLine("Hello, World!");
|
|
#region 知识点二 成员方法的使用
|
|
Person p = new Person();
|
|
p.name = "HK";
|
|
p.age = 18;
|
|
p.Speak("hello");
|
|
Console.WriteLine(p.IsAdult() ? "成年了" : "没成年");
|
|
Person p2 = new Person();
|
|
p2.name = "KH";
|
|
p2.age = 18;
|
|
p.AddFriend(p2);
|
|
for (int i = 0; i < p.friend.Length; i++)
|
|
{
|
|
Console.WriteLine("{0}是{1}的朋友",p.friend[i].name,p.name);
|
|
}
|
|
#endregion
|
|
}
|
|
}
|
|
}
|