C#动态方法调用 提高程序的扩展性

此篇将介绍C#如何在运行时动态调用方法。当某些类型是运行时动态确定时,编译时的静态编码是无法解决这些动态对象或类的方法调用的。此篇则给你一把利剑,让动态对象的方法调用成为可能。

1.动态调用dll里的方法

[csharp] view plaincopyprint?

  1. <span style="font-family:SimSun;font-size:12px;">/// <summary>
  2. /// 该类将被独立编入Class1.dll汇编
  3. /// </summary>
  4. class Class1
  5. {
  6. public static string method1()
  7. {
  8. return "I am Static method (method1) in class1";
  9. }
  10. public string method2()
  11. {
  12. return "I am a Instance Method (method2) in Class1";
  13. }
  14. public string method3(string s)
  15. {
  16. return "Hello " + s;
  17. }
  18. }
  19. /// <summary>
  20. /// 该类独立放入Test.exe汇编
  21. /// </summary>
  22. class DynamicInvoke
  23. {
  24. public static void Main(string[] args)
  25. {
  26. // 动态加载汇编
  27. string path = "Class1.dll";
  28. Assembly assembly = Assembly.Load(path);
  29. // 根据类型名得到Type
  30. Type type = assembly.GetType("Class1");
  31. // 1.根据方法名动态调用静态方法
  32. string str = (string)type.InvokeMember("method1", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] { });
  33. Console.WriteLine(str);
  34. // 2.根据方法名动态调用动态对象的成员方法
  35. object o = Activator.CreateInstance(type);
  36. str = (string)type.InvokeMember("method2", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, new object[] { });
  37. Console.WriteLine(str);
  38. // 3.根据方法名动态调用动态对象的有参成员方法
  39. object[] par = new object[] { "kunal" };
  40. str = (string)type.InvokeMember("method3", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, par);
  41. Console.WriteLine(str);
  42. // 带out修饰的InvokeMember
  43. // System.Int32 中 public static bool TryParse(string s, out int result) 方法的调用
  44. var arguments = new object[] { str, null }; // 注意这里只能将参数写在外面,out参数为null也没有关系
  45. typeof(int).InvokeMember("TryParse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static,
  46. null, null, arguments);
  47. Console.WriteLine(arguments[1]);
  48. }
  49. }</span>

2.动态加载类文件并调用方法:

[csharp] view plaincopyprint?

  1. <span style="font-family:SimSun;font-size:12px;">using System;
  2. using System.CodeDom.Compiler;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Threading;
  6. using System.Windows.Forms;
  7. using Microsoft.CSharp;
  8. namespace _32.DynamicReflection
  9. {
  10. internal class Program
  11. {
  12. private static void Main(string[] args)
  13. {
  14. #region 内置标签方法 (动态加载)
  15. const string className = "DynamicReflection.Test"; //类名称一定要全称
  16. string fileName = <strong>Thread.GetDomain().BaseDirectory + "Test.cs";</strong>
  17. if (File.Exists(fileName))
  18. {
  19. var sourceFile = new FileInfo(fileName);
  20. CodeDomProvider provider = new CSharpCodeProvider();
  21. var cp = new CompilerParameters();
  22. cp.ReferencedAssemblies.Add("System.dll"); //添加命名空间引用
  23. cp.GenerateExecutable = false; // 生成类库
  24. cp.GenerateInMemory = true; // 保存到内存
  25. cp.TreatWarningsAsErrors = false; // 不将编译警告作为错误
  26. // 编译
  27. CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile.FullName);
  28. if (cr.Errors.Count < 1)
  29. {
  30. Assembly asm = cr.CompiledAssembly; // 加载
  31. //1.调用静态方法
  32. Type type = asm.GetType(className);
  33. var str =(string)type.InvokeMember("SayHello1", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] {});
  34. Console.WriteLine(str);
  35. //2.调用实例方法
  36. object instance = asm.CreateInstance(className);
  37. str =(string)type.InvokeMember("SayHello2", BindingFlags.Default | BindingFlags.InvokeMethod, null, instance,new object[] {});
  38. Console.WriteLine(str);
  39. //3.调用带参数的方法
  40. var par = new object[] {"zhangqs008"};
  41. str =(string)type.InvokeMember("SayHello3", BindingFlags.Default | BindingFlags.InvokeMethod, null, instance,par);
  42. Console.WriteLine(str);
  43. Console.Read();
  44. }
  45. else
  46. {
  47. string msg = null;
  48. for (int index = 0; index < cr.Errors.Count; index++)
  49. {
  50. CompilerError error = cr.Errors[index];
  51. msg += "【错误" + (index + 1) + "】" + Environment.NewLine;
  52. msg += "[文件] " + error.FileName + Environment.NewLine;
  53. msg += "[位置] 行" + error.Line + ",列" + error.Column + Environment.NewLine;
  54. msg += "[信息] " + error.ErrorText + Environment.NewLine;
  55. msg += Environment.NewLine;
  56. }
  57. MessageBox.Show(msg, "内置方法类编译错误");
  58. }
  59. }
  60. #endregion
  61. }
  62. }
  63. }</span>

类文件:

[csharp] view plaincopyprint?

    1. <span style="font-family:SimSun;font-size:12px;">namespace DynamicReflection
    2. {
    3. public class Test
    4. {
    5. public static string SayHello1()
    6. {
    7. return "hello static method";
    8. }
    9. public string SayHello2()
    10. {
    11. return "hello instance method";
    12. }
    13. public string SayHello3(string args)
    14. {
    15. return "hello args " + args;
    16. }
    17. }
    18. }
    19. </span>
时间: 2024-08-27 08:02:27

C#动态方法调用 提高程序的扩展性的相关文章

JDK7动态方法调用

在JDK7中,Java提供了对动态语言特性的支持,实现了JSR 292 <Supporting Dynamically Typed Languages on the Java Platform>规范,这是Java语言发展的一重大进步,而提供对动态语言特性支持也是Java发展的一大趋势与方向.那么动态性表现在哪里呢?其一在Java API层面,新增了java.lang.invoke包,主要包含了CallSite.MethodHandle.MethodType等类:其二,在Java字节码指令层面,

第三章Struts2 Action中动态方法调用、通配符的使用

01.Struts 2基本结构 使用Struts2框架实现用登录的功能,使用struts2标签和ognl表达式简化了试图的开发,并且利用struts2提供的特性对输入的数据进行验证,以及访问ServletAPI时实现用户会话跟踪,其简单的程序运行流程图如下 Struts2框架是基于MVC模式.基于MVC模式框架的核心就是控制器对所有请求进行统一处理.Struts2的控制器StrutsPrepareAndExecuteFilter由ServletAPI中的Filter充当,当web容器的接收到登录

Struts2学习第七课 动态方法调用

动态方法调用:通过url动态调用Action中的方法. action声明: <package name="struts-app2" namespace="/" extends="struts-default"> <action name="Product" class="org.simpleit.app.Product"> </package> URI: --/strut

动态方法调用

1.先建立一个项目 2.在此项目中需要建立两个jsp 1)在第一个jsp中写入一句话 <body> User Add Success! </body> 2)在第二个jsp中写入链接 <body> Action执行的时候并不一定要执行execute方法<br /> 可以在配置文件中配置Action的时候用method=来指定执行哪个方法 也可以在url地址中动态指定(动态方法调用DMI)(推荐)<br /> <a href="<

struts2中通配符和DMI(动态方法调用)

在struts2中不建议使用Dynamic Method Invocation,具体原因见官方文档: http://struts.apache.org/docs/action-configuration.html#ActionConfiguration-WildcardMethod; 刚刚接触这块,所以两种方法各自实现一下: 1)动态方法调用: struts.xml文件: <package name="default" namespace="/yin" ext

Struts2动态方法调用(DMI)

在Struts2中动态方法调用有三种方式,动态方法调用就是为了解决一个Action对应多个请求的处理,以免Action太多 第一种方式:指定method属性这种方式我们前面已经用到过,类似下面的配置就可以实现 <action name="chainAction" class="chapter2.action.Chapter2Action" method="chainAction"> <result name="chai

C#动态方法调用

此篇将介绍C#如何在运行时动态调用方法.当某些类型是运行时动态确定时,编译时的静态编码是无法解决这些动态对象或类的方法调用的.此篇则给你一把利剑,让动态对象的方法调用成为可能. 1.动态调用dll里的方法: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

struts2.5动态方法调用和默认Action

在动态方法调用中,使用通配符方法出现问题,参考了http://www.cnblogs.com/jasonlixuetao/p/5933671.html 这篇博客,问题解决了. 这个是helloworld.xml: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Co

ActionMethod_DMI_动态方法调用

Action执行的时候并不一定要执行execute方法可以在配置文件中配置Action的时候用method=来指定执行那个方法,也可以在url地址中动态指定(动态方法调用DMI)(推荐) 动态方法调用的配置要先打开: 1 <constant name="struts.enable.DynamicMethodInvocation" value="true"/> index.jsp 1 <%@ page language="java"