- namespace 反射
- {
- class Program
- {
- static void Main(string[] args)
- {
- //Assembly ass = Assembly.LoadFile(@"d:/Demo.dll");
- //Type type = ass.GetType("Demo.ReflectCLASS");
- System.Reflection.Assembly ass;
- Type type ;
- object obj;
- try
- {
- ass = System.Reflection.Assembly.LoadFile(@"d:/Demo.dll");
- type = ass.GetType("Demo.ReflectCLASS");//必须使用名称空间+类名称
- System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名称
- obj = ass.CreateInstance("Demo.ReflectCLASS");//必须使用名称空间+类名称
- string s = (string)method.Invoke(obj, new string[] { "jianglijun" }); //实例方法的调用
- Console.WriteLine(s );
- method = type.GetMethod("WriteName");//方法的名称
- s = (string)method.Invoke(null, new string[] { "jianglijun" }); //静态方法的调用
- Console.WriteLine(s);
- method = type.GetMethod("WriteNoPara");//无参数的实例方法
- s = (string)method.Invoke(obj, null);
- Console.WriteLine(s );
- method = null;
- }
- catch(Exception ex)
- {
- }
- }
- }
- }
有关使用反射调用方法的Demo
最新推荐文章于 2024-12-31 08:58:28 发布
本文介绍了一个使用C#反射来加载程序集、获取类型、创建对象并调用其方法的示例。通过反射可以动态地执行类的方法,包括实例方法、静态方法及无参数方法。
1351

被折叠的 条评论
为什么被折叠?



