C# 反射机制
C# 是一种面向对象的编程语言,但是通过反射机制,可以访问到类内部私有(即private)的成员和函数。
using System.Reflection;
1 public static class DrawGraphics 2 { 3 private static Graphics drawRGB,drawDepth; 4 private static Size drawRGBSize,drawDepthSize; 5 public static void drawPicture(string name, Bitmap image) 6 { 7 BindingFlags flag = BindingFlags.Static | BindingFlags.NonPublic; 8 FieldInfo draw = typeof(DrawGraphics).GetField("draw" + name, flag); 9 FieldInfo drawSize = typeof(DrawGraphics).GetField("draw" + name + "Size", flag);10 Graphics drawG = (Graphics)draw.GetValue(null);11 Size drawS = (Size)drawSize.GetValue(null);12 if (drawG!=null)13 drawG.DrawImage(new Bitmap(image, drawS), zeroPoint);
14 }15 }
通过这种方式,可以动态的根据字符串的值来调用相应的函数、获得相应的变量。
TAG: