传智 赵建宇 C#基础课程整理
static 和 Non-static class 的区别
- 在非静态类中,既有实例成员,也可以有静态成员。
- 在调用实例成员的时,使用 对象名.实例成员名;
在调用静态成员的时,使用 类名.静态成员名;总结:
- 静态成员必须使用类名去调用,而实例成员使用对象名调用、
- 静态函数中,只能访问静态成员 ,不允许访问实例成员。
- 实例函数中,既可以使用静态成员,也可以使用实例成员。
- 静态类中只允许有静态成员,不允许出现实例成员。
使用:
- 如果你想要你的类当做一个“工具类”去使用, 这个时候可以考虑将类写成静态类。 例如:Console.WriteLine()
- 静态类在整个项目中资源共享
- 只有程序全部结束的时候,静态类才会释放资源。
构造函数
作用: 初始化对象 (给对象的每个属性一次的赋值)
构造函数是一个特殊方法:
- 构造函数没有返回值,连 void 也不能写。
- 构造函数的名称必须跟类名一样。
创建对象的时候会执行构造函数
构造函数是可以有重载的
new关键字
new 帮助我们做三件事
- 在内存中开辟一块空间
- 在开辟的空间中创建对象
- 调用对象的构造函数进行初始化对象
This 关键字
- 代表当前类的对象
- 在类当中显示的调用本类的构造函数 :this()
class test
{
private string _name;
public string Name{
set{this._name = value;}
get{return this._name;}
}
int _age;
public int Age{
set{this._age = value;}
get{return this._age;}
}
string _gender;
public sting Gender{
set{this._gender = value;}
get{return this._gender;}
}
int _chinese;
public int Chinese{
set{this._chinese = value;}
get{return this._chinese;}
}
int _english;
public int English{
set{this._english = value;}
get{return this._english;}
}
int _math;
public int Math{
set{this._math = value;}
get{return this._math;}
}
public test(string a, int b, string c, int d, int e, int f)
{
this.Name = a;
this.Age = b;
this.Gender = c;
this.Chinese = d;
this.English = e;
this.Math = f;
}
public test(string a, int b, int c, int d) : this(a, 0, "male", b, c, d){}
}
命名空间
引用同一个solution下其它project 里的类
- 添加引用
- 引用命名空间
值类型和引用类型
区别:
- 值类型和引用类型在内存上存储的地方不一样
- 在传递值类型和传递引用类型的时候,传递的方式不一样。
值类型我们称之为值传递,引用类型我们称之为引用传递。
值类型和引用类型:
- 值类型: int , double , bool, char, decimal, struct, enum
- 引用类型: string, 自定义类, 数组
存储:
- 值类型的值是存储在内存的栈当中。(栈内存放数值)
- 引用类型的值存储在堆当中。(堆内存放数值,栈内存放指向堆的地址)
字符串
- 字符串的不可变性:给字符串重新赋值时, 不会删除原来内存中的内容,而是重新开辟空间存储新值,之后指向新值。
- 长度 string.length
- .ToUpper()
- .ToLower()
- s1.Equals(s2, StringComparison.OrdinalIgnoreCase)
- 分割字符串 s.Split()
- .Contains(“str1”)
- .Replace(“str1”, “str2”)
- .Substring()
- StartsWith()
- EndsWith()
- IndexOf();
- LastIndexOf()
- Trim()
- TrimStart()
- TrimEnd()
- IsNullOrEmpty()
- .Join()
继承
子类 派生类
父类 基类
子类继承了父类,那么子类从父类继承了public field, public property 和 public methods. 不能继承 private field, private property 和 private methods.
子类继承 具有单根性
子类继承 具有传递性
子类没有继承父类的构造函数,但是,子类会默认调用父类的无参的构造函数, 创建父类对象,让子类可以使用父类中的成员。所以,如果在父类中重新写了一个有参数的构造函数之后,那个无参数的就被干掉了,子类就调用不到了,所以子类会报错。
解决办法:
- 在父类中重新写一个无参数的构造函数,在在子类中定义需要的构造函数。
- 在子类中显示的调用父类的构造函数,使用关键字 :base()
public class Children : Parent { public Children() : base(...) { ... } }