良心与思想

偶的代码生涯
随笔 - 32, 评论 - 243, 引用 - 31

导航

关于

最近在学习windbg

标签

每月存档

最新留言

广告

关于InvokeMember的一个郁闷的错误

背景:两个CustomControl,一个叫做MyPanel,是一个M*N的格子,一个叫做Ball,是一个球。球可以放在panel的格子中,可以鼠标进行drag & drop.

直接call很简单,没有任何问题。但是通过reflection,碰到了郁闷的事情。虽然最终搞定了,但是要看过InvokeMember的代码才能知道为什么。

代码:

        Object panel = null;
        Type tpanel = null;

        private void ReflectionForm_Load(object sender, EventArgs e)
        {
            Assembly asm = Assembly.LoadFile(@"D:\test\WindowsApplication5\MyLibrary\bin\Debug\mylibrary.dll");
            tpanel = asm.GetType("MyLibrary.MyPanel");
            panel = tpanel.InvokeMember("", BindingFlags.CreateInstance, null, this, new object[] { });

            (panel as Control).Location = new Point(100, 100);
            this.Controls.Add(panel as Control);                          
        }

出错的地方:

tpanel.InvokeMember("AddBall", BindingFlags.Instance | BindingFlags.Public|BindingFlags.InvokeMethod,
                null, panel, new object[] { obj });

如果上面的panel是object类型,那么一切正常。如果是Control类型,即,我声明为:Control panel,然后
object obj = tpanel.InvokeMember("", BindingFlags.CreateInstance, null, this, new object[] { });
panel = object as Control;
panel.Location = new Point(100,100);
this.Controls.Add(panel);

那么上面的InvokeMember就会提示我:Method not found!如果我修改BindingFlags,去掉Method,那么没有MethodNotFound的exception,但是会有“请使用InvokeMethod,Set/Get Field之类的提示”。如果加上,就是MethodNotFound,真是faint!

google了一些,貌似有些人碰到过,一个post上面说,arguments的类型必须要和method的类型完全一致才可以。我想,如果Panel当作control来用,那么control -> Ball类型会无法转换的,而object -> Ball是允许的。

哪位高手帮忙解释一下?谢谢!

posted on 2007-08-08 21:20:00 by juqiang  评论(10) 阅读(6351)

Powered by: Joycode.MVC引擎 0.5.2.0