您的位置:首页 > 编程语言 > C#

C# 针对静态类的反射,静态成员同理

2014-01-21 11:10 218 查看
原链接:http://bbs.csdn.net/topics/340014300#post-340683803

一个最简单的C#反射实例,首先编写类库如下:
namespace ReflectionTest
{
public class WriteTest
{
//带参数的公共方法
public void WriteString(string s, int i)
{
Console.WriteLine("WriteString:" + s + i.ToString());
}
//带一个参数的静态方法
public static void StaticWriteString(string s)
{
Console.WriteLine("StaticWriteString:" + s);
}
//不带参数的静态方法
public static void NoneParaWriteString()
{
Console.WriteLine("NoParaWriteString");
}
}
}

class TestApp
{
public static void Main()
{
Assembly ass;
Type type;
Object obj;
//用来测试静态方法
Object any = new Object();
//指定类库文件必须使用绝对路径,不能使用相对路径
ass = Assembly.LoadFile(@"D:\Source Code\00.C#Sudy\01.Reflection\01\ReflectTest.dll");
//命名空间和类的名字必须一起指定
type = ass.GetType("ReflectionTest.WriteTest");

/**//*example1---------*/
MethodInfo method = type.GetMethod("WriteString");
string test = "test";
int i = 1;
Object[] parametors = new Object[]{test,i};
//在例子1种必须实例化反射要反射的类,因为要使用的方法并不是静态方法。
//创建对象实例
obj = ass.CreateInstance("ReflectionTest.WriteTest");
//执行带参数的公共方法
method.Invoke(obj, parametors);
//method.Invoke(any, parametors);//异常:必须实例化反射要反射的类,因为要使用的方法并不是静态方法。

/**//*example2----------*/
method = type.GetMethod("StaticWriteString");
method.Invoke(null, new string[] { "test"}); //第一个参数忽略
//对于第一个参数是无视的,也就是我们写什么都不会被调用,
//即使我们随便new了一个any这样的Object,当然这种写法是不推荐的。
//但是对应在例子1种我们如果Invoke的时候用了类型不一致的实例来做为参数的话,将会导致一个运行时的错误。
method.Invoke(obj, new string[] { "test"});
method.Invoke(any, new string[] { "test"});

/**//*example3-----------*/
method = type.GetMethod("NoneParaWriteString"); //调用无参数静态方法的例子,这时候两个参数我们都不需要指定,用null就可以了。s
method.Invoke(null, null);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: