c#反射实例学习

发布时间:2019-11-10编辑:脚本学堂
介绍:C#反射提供了封装程序集、模块和类型的对象等。可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。

如果代码中使用了属性,可以利用反射对它们进行访问。

首先,举一个比较简单的应用c#反射的例子。
编写类库:
 

复制代码 代码示例:
using System;
namespace ReflectionTest
{
public class WriteTest
{
//public method with parametors
public void WriteString(string s, int i)
{
Console.WriteLine("WriteString:" + s + i.ToString());
}
//static method with only one parametor
public static void StaticWriteString(string s)
{
Console.WriteLine("StaticWriteString:" + s);
}
//static method with no parametor
public static void NoneParaWriteString()
{
Console.WriteLine("NoParaWriteString");
}
}
}

使用命令行编译csc /t:library ReflectTest.cs命令进行编译,生成ReflectTest.dll库文件。
 

复制代码 代码示例:
using System;
using System.Reflection;
class TestApp
{
public static void Main()
{
Assembly ass;
Type type;
Object obj;
Object any = new Object();
ass = Assembly.LoadFile(@"D:Source Code0.C# Sudy1.Reflection1ReflectTest.dll");
type = ass.GetType("ReflectionTest.WriteTest");
/*example1---------*/
MethodInfo method = type.GetMethod("WriteString");
string test = "test";
int i = 1;
Object[] parametors = new Object[] { test, i };
obj = ass.CreateInstance("ReflectionTest.WriteTest");
method.Invoke(obj,//Instance object of the class need to be reflect
parametors);
//method.Invoke(any, parametors);//RuntimeError: class reference is wrong
/*example2----------*/
method = type.GetMethod("StaticWriteString");
method.Invoke(null, new string[] { "test" });
method.Invoke(obj, new string[] { "test" });
method.Invoke(any, new string[] { "test" });
/*example3-----------*/
method = type.GetMethod("NoneParaWriteString");
method.Invoke(null, null);
}
}

学习C#反射的几点注意事项:
1、指定类库文件必须使用绝对路径,不能使用相对路径
2、19行,命名空间和类的名字必须一起指定
3、在例子1种必须实例化反射要反射的类,因为要使用的方法并不是静态方法。
4、由于这个方法有两个参数,可以用这种Object的方法指定参数也可以直接写method.Invoke(obj, new Object[] { "test", 1 });
5、在例子2种我们想用的方法是一个静态方法,这时候Invoke的时候,对于第一个参数是无视的,也就是我们写什么都不会被调用,即使我们随便 new了一个any这样的Object,当然这种写法是不推荐的。但是对应在例子1种我们如果Invoke的时候用了类型不一致的实例来做为参数的话,将 会导致一个运行时的错误。
6、第三个例子是一个调用无参数静态方法的例子,这时候两个参数我们都不需要指定,用null就可以了。

另外,如果调用的类是静态类的时候,需要注意,静态类是不能实例化的,这时候,31行的类的实例化的方法就不需要了,直接使用Invoke就可以实现,否则将会出现运行时的错误,同样的道理,第一个参数将会被无视,只要我们传对了参数就可以了。

您可能感兴趣的文章:
C#学习笔记之反射举例
c# 反射加载的实例代码
C#反射实例学习入门