1.反射:反射是.net中的重要机制,通过反射可以在运行时获得.net中每一个类型,包括类、结构、委托和枚举的成员,包括方法、属性、事件,以及构造函数等。有了反射,既可以对每一个类型了如指掌。
下面来演示一下反射的实例
(1)新建一个类库项目。在解决方案上单击右键选择添加“新建项目”,在弹出来的框中选择“类库”,在下面名字栏中输入clalib。然后删除cla1类,新添加一个类“claperson”,添加如下代码:
namespace clalib
{
public cla claperson
{
public claperson():this(null)
{
}
public claperson(string strname)
{
name = strname;
}
private string name;
private string sex;
private int age;
public string name
{
get { return name; }
set { name = value; }
}
public string sex
{
get { return sex; }
set { sex = value; }
}
public int age
{
get { return age; }
set { age = value; }
}
public void sayhello()
{
if (null==name)
console.writeline(\"hello world\");
else
console.writeline(\"hello,\" + name);
}
}
}
添加完之后编译生成一下,就会在这个类库项目中的bin\\debug中有一个clalib.dll文件。然后添加一个控制台应用程序。引入system.reflaction的命名空间。添加的代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.reflection;//添加反射的命名空间
namespace consoleapplication4
{
public cla program
{
static void main(string[] args)
{
console.writeline(\"列出程序集中的所有类型\");
aembly a = aembly.loadfrom(\"clalib.dll\");
type[] mytype = a.gettypes();
type claperson = null;
foreach (type p in mytype)
{
console.writeline(p.name);
if (p.name==\"claperson\")
{
claperson = p;
}
}
console.writeline(\"列出clapersonl类中的所有的方法\");
methodinfo[] md = claperson.getmethods();
foreach(methodinfo m in md)
{
console.writeline(m.name);
}
console.writeline(\"实例化claperson类,并调用sayhello方法\");
object obj = activator.createinstance(claperson);
object objname=activator.createinstance(claperson,\"飞鹰\");
methodinfo mysayhello = claperson.getmethod(\"sayhello\");
mysayhello.invoke(obj, null);//无参数构造函数
mysayhello.invoke(objname, null);//有参构造函数
console.readkey();
}
}
}
运行之后的结果是:
列出程序集中的所有类型
claperson
列出clapersonl类中的所有的方法
get_name
set_name
get_sex
set_sex
get_age
set_age
sayhello
tostring
equals
gethashcode
gettype
实例化claperson类,并调用sayhello方法
hello world
hello,飞鹰
2.using的作用
(1)引入命名空间,如:using system。
(2)using别名。
格式:using 别名=包括详细命名空间信息的具体的类型
例如:在两个命名空间(namespace1,namespace2)里各有一个mycla类,这时可以这样引入命名空间,
using acla=namespace1.mycla;
using bcla=namespace2.mycla;
实例化时:
acla my1=new acla;
bcla my2=new bcla;
(3)using定义范围
即时释放资源,在范围结束时处理对象。例如:
using(cla1 cls1=new cla1())
{
}
在这个代码段结束时会触发cls1的dispose方法释放资源。