Object类
- 对于C#中所有Class,默认的父类或最终基类都是Object类(System命名空间下,简称为object)
ToString();
- 默认情况:答应输出当前对象类型全名(namespace + class)
- 用途:特定的打印输出需求,可以重写ToString
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
//用途:Debug的时候打印对象信息
public override string ToString()
{
string result = "";
result += $"学号:{Id}\n";
result += $"年龄:{Age}\n";
result += $"名字:{Name}\n";
return result;
}
}
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.Name = "张三";
s.Age = 18;
s.Id = 1;
Console.WriteLine(s.ToString());
Console.ReadKey();
}
}
Type
- 用于获取当前对象的类型信息(反射)
- FullName:完整类型名,命名空间+类名
- Name:类名
- IsValueType:是否是值类型
- IsClass:是否是引用类型
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Student s = new Student();
//获取类型信息
ShowType(s);
Console.ReadKey();
}
static public void ShowType(object o)
{
Type type = o.GetType();
Console.WriteLine(type.FullName);
Console.WriteLine(type.Name);
Console.WriteLine(type.IsValueType); //是不是值类型
Console.WriteLine(type.IsClass); //是不是引用类型
}
}
Equals()
- 用于判断两个对象是否相等,于"=="一致
- ==:值类型的值相同、引用类型的地址相同、字符串的字符相同
- 需求:有时候我们有特定的相等判定需求,比如两个对象id相同才算相等、各个成员变量相同才算相等
- 方法:对Equals方法进行重写
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public override bool Equals(object obj)
{
// 1 尝试将obj转化为Student类型对象
Student other = obj as Student;
// 2 如果转化不成功,二者不具备可比性
if (other == null) return false;
// 3 如果转化成功,则二者参数一一对比
return Name == other.Name && Age == other.Age && Id == other.Id;
}
}
class Program
{
static void Main(string[] args)
{
Student s0 = new Student();
s0.Name = "张三";
s0.Age = 18;
s0.Id = 1;
Student s1 = new Student();
s1.Name = "张三";
s1.Age = 18;
s1.Id = 1;
Console.WriteLine(s0.Equals(s1));
Console.ReadKey();
}
}
装箱与拆箱
- 装箱:将值类型转换为Object类型的过程
- 拆箱:将Object中提取值类型的过程
//装箱
int i=123;
object o = i; //将i的int变成object,将数字i装入对象o当中
//拆箱
int j = (int)o;
将各类数据装入同一个数组的过程,{1,3.4,“abc”}
static void Main(string[] args)
{
//请编写一个数组,{1,2.5,"abc",cat}
// 1 装箱&拆箱
// 2 object作为基类
Cat cat = new Cat();
//对于1跟2.5这种值类型,都进行了装箱操作
//1装入obj0当中,放到了objs数组的0号位
//2.5装入obj1当中,放到了objs数组的1号位
//"abc"是引用类型,string类型的对象,因为string的祖宗是object
//cat是引用类型,是Cat类的对象,因为Cat的父类/祖宗是object类
object[] objs = { 1, 2.5, "abc", cat };
Console.ReadKey();
}