属性
为类设置属性,可以通过get和set来获取信息,这样,可以设置私有元素。
一般属性的开头用大写字母(ep:Name)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study1_repeat
{
class Program
{
static void Main(string[] args)
{
classText ct = new classText("李刚");
Console.WriteLine(ct.Name);
ct.Name = "刘明";
Console.WriteLine(ct.Name);
Console.ReadLine();
}
}
//添加一个类
class classText {
//私有元素
private String name;
public classText(){
Console.WriteLine("ceshi");
}
public classText(String name) {
this.name = name;
}
//设置属性
//设置好属性后,可以通过调用Name的方法
public String Name {
get {//返回元素,获取属性
return name;
}
set {
//使得name获得相应的元素,设置属性
//对应:ct.Name = "刘明";
name = value;
}
}
}
}
方法
修饰符 返回类型 方法名称(参数列表)
{
方法体;
}
如果写返回类型,就必须要用return返回一个和返回类型相同的值。
如果不写返回类型,就要用void。
静态方法和实例方法
使用static关键字
- 静态方法属于类本身,不属于任何对象。静态方法只能对类中的静态成员进行访问,不能对特定对象进行操作。所以静态方法中不能用this。静态方法运行时,并不一定存在对象。
- 实例方法可以使用类的任何成员。实例方法可以访问静态和实例成员。
实例变量:
int i
静态变量:
static int i
实例方法:
void example(){}
静态方法:
static void example(){}