曾英-C#教学-44 命名空间和装箱拆箱
目录
- 1\认识命名空间,学习如何定义使用命名空间
- 2\学习如何使用帮助
- 3\理解装箱和拆箱操作
1\命名空间
- 以下都是.Net内部定义的命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace是自己定义的
namespace _44_命名空间
1.1\namespace
- 如果没有定义不同的命名空间的话,在出现相同类的时候会出错.
- 命名空间可以区分各种累进入不同的类(或者同名的类)进入不同的命名空间
程序实例:
调用不同命名空间中的类的方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//类库
namespace _44_命名空间
{
class Program
{
static void Main(string[] args)
{
//引用别的命名空间的类的方法:
//在类名前添加一个命名空间的名字
A.Bird f1 = new A.Bird();
f1.Fly(); //输出结果:A小鸟飞.
//引用B命名空间的方法:
B.Bird f2 = new B.Bird();
f2.Fly();//输出结果:B小鸟飞.
}
}
}
//类库
namespace A
{
class Bird
{
public void Fly()
{ Console.WriteLine("A小鸟飞"); }
}
}
namespace B
{
class Bird
{
public void Fly()
{ Console.WriteLine("B小鸟飞"); }
}
}
1.2\没有命名空间的时候的处理方法
程序实例:
//using System; //这里using System被注释了
/*using System.Collections.Generic;
using System.Linq;
using System.Text;
*/
namespace _44_2
{
class Program
{
static void Main(string[] args)
{
//主函数中每一个方法的前面都需要增加一个System.xxx来实现调用系统方法.
double a = 4;
double b = System.Math.Sqrt(a);
System.Console.WriteLine(b);
string cc = System.Console.ReadLine();
int d = System.Convert.ToInt32(b);
}
}
}
1.3\多种命名空间
1.4\嵌套类型命名空间的调用
using System;
namespace _44_3_命名空间
{
class Program
{
static void Main(string[] args)
{
//定义的时候要将两个命名空间依次写出
A.AA.bird f1=new A.AA.bird();
f1.Fly();
}
}
}
//这里套用了两层命名空间.
namespace A
{
namespace AA
{
class bird
{
public void Fly()
{ Console.WriteLine("a小鸟飞"); }
}
}
namespace AB
{ }
}
2\使用帮助
msdn
3\装箱和拆箱
-
C#的类型分为值类型和引用类型,
-
值类型:装箱前n的值存储在栈中,
-
引用类型:装箱后n的值被封装到堆中.
-
这里,什么类型都能赋给object型.但是会损失性能.
- 这里用object类来进行装箱操作
程序实例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//这里如果添加一个 using Ct,主函数中定义的时候就不需要写 Ct.Storehouse store = new Ct.Storehouse(5);中的Ct.
namespace _44_装拆箱
{
class Program
{
static void Main(string[] args)
{
Ct.Storehouse store = new Ct.Storehouse(5);
//可以使用各种类型
store.Add(100);
store.Add(2.14);
store.Add("good");
store.Add(new Ct.Storehouse(5));
//遍历
//这里是装箱操作,将多种数据类型都用object类型.
foreach (object item in store.Items)
{ Console.WriteLine(item); }
}
}
}
namespace Ct
{
class Storehouse
{
//object型数组,可以存储各种类型数据
public Object[] Items;
private int count;
//这里用count为数组计数
public Storehouse(int size)
{
//数组的初始化
Items = new Object[size];
count = 0;
}
//数组中添加数据
//为Items添加数据,并判断数组是否溢出
public void Add(Object obj)
{
if (count < Items.Length)
{
Items[count] = obj;
count++;
}
else Console.WriteLine("仓库已满");
}
}
}