第四章
一: System.Object的公有方法:
Equals();
GetHashCode();
ToString();
GetType();
下面的是对GetType的一个例子:
using System;
using System.Collections.Generic;
using System.Text;
namespace GetType
{
class Program
{
static void Main(string[] args)
{
Person person = new Person();
//person.GetType();返回一个类型
int i = 2;
Console.WriteLine(person.GetType());
Console.WriteLine(i.GetType());
Console.WriteLine(person.Equals(i));
}
}
}
输出:GetType.Person
System.Int32
False
二:类型转换
using System;
using System.Collections.Generic;
using System.Text;
namespace Leixing
{
class Program
{
static void Main(string[] args)
{
Object o = new Employee();
//这里不需要转换,因为new返回的是一个Employee对象
//而Object又是Employee的基类型
Console.WriteLine(o.GetType());
Employee e = (Employee)o;
//需要转换,因为Employee继承自Object
Console.WriteLine(e.GetType());
Manager m = new Manager();
//Manager继承了Employee
PromoteEmployee(m);
Console.WriteLine(m.GetType());
//DateTime newYears = new DateTime(2008,9,11);
//PromoteEmployee(newYears);
//无法将类型为“System.DateTime”的对象强制转换为类型“Leixing.Employee”
}
public static void PromoteEmployee(object o)
{
Employee e = (Employee)o;
}
}
}
三:is 和as 操作符
is可以家对象是否和给定的类型兼容,并返回判断结果:true或false.另外,is永远不会抛出异常.如果对象引用为null,那么is总是返回false,因为没有对象可以用来检查其类型.
as 如果兼容,返回一个指向同一个对象的非空指针.否则,as返回null.如果不能顺利转换,会抛出一个异常.
using System;
using System.Collections.Generic;
using System.Text;
namespace IsAndAs
{
class Program
{
static void Main(string[] args)
{
Object o = new Object();
bool b1=(o is Employee);
bool b2=(o is Object);
Console.WriteLine(b1);
Console.WriteLine(b2);
Manager m = new Manager();
//Manager是Employee的派生类
if (m is Employee)
{
Employee e = (Employee)m;
//下面开始对e写语句
Console.WriteLine(e.GetType());
}
Manager m1 = new Manager();
Employee e1=m as Employee;
if(e1!=null)
{
//下面开始对e1写语句
Console.WriteLine(e1.GetType());
}
}
}
}
四:引用类型和值类型
引用类型:
1.内存必须从托管堆中分配;
2.每个在托管堆中分配的对象都有一些与之关联的额外附加成员必须被初始化;
3.从托管堆中分配对象可能会导致执行垃圾收集。
struct SomeVal
{
public int x;
}
class SomeRef
{
public int x;
}
class Program
{
static void Main(string[] args)
{
SomeRef r1 = new SomeRef();
SomeVal v1 = new SomeVal();
r1.x = 5;
v1.x = 5;
Console.WriteLine(r1.x);
Console.WriteLine(v1.x);
SomeRef r2 = r1;
SomeVal v2 = v1;
r1.x = 8;
v1.x = 9;
Console.WriteLine(r1.x);
Console.WriteLine(r2.x);
Console.WriteLine(v1.x);
Console.WriteLine(v2.x);
}
}
结果:
5
5
8
8
9
5
五:值类型的装箱与拆箱
struct SomeVal
{
public int x,y;
}
class SomeRef
{
public int x;
}
class Program
{
static void Main(string[] args)
{
SomeRef r1 = new SomeRef();
SomeVal v1 = new SomeVal();
r1.x = 5;
v1.x = 5;
Console.WriteLine(r1.x);
Console.WriteLine(v1.x);
SomeRef r2 = r1;
SomeVal v2 = v1;
r1.x = 8;
v1.x = 9;
Console.WriteLine(r1.x);
Console.WriteLine(r2.x);
Console.WriteLine(v1.x);
Console.WriteLine(v2.x);
ArrayList a = new ArrayList();
SomeVal p;
for (int i = 0; i < 10; i++)
{
p.x = p.y = 1;
a.Add(p);
}
SomeVal x=(SomeVal)a[0];
Console.WriteLine(x);
}
}