开发者

How to call a specific method on an object after creating it via its constructor using reflection in .NET?

开发者 https://www.devze.com 2023-03-01 02:27 出处:网络
I have a WPF application that I want to launch using: Assembly.LoadFrom It works fine but after this, I am trying to call it\'s default constructor:

I have a WPF application that I want to launch using:

Assembly.LoadFrom

It works fine but after this, I am trying to call it's default constructor:

LayerView.MainWindow();

Then, call the Show method on the created instance.

I tried using:

assembly.GetTypes();

Looping through them and then when I find the right type LayerView.MainWindow, then call:

c.getConstructors ();

Looping through them and when I find the right ctor开发者_如何转开发, call:

ctor.Invoke (null);

but not sure if it works because after creating the instance, nothing is visible. I have to call the Show method and that's where I am stuck. I don't know how to access the created instance.

Also is this the best way to do this? It seems pretty clunky to loop through these to find the right one. Maybe this could be made better using Linq?


Try casting the result of ctor.Invoke(null) to the type of object you're expecting. Here's an example (note: I'm not sure exactly what constructor your calling, so you'll need to figure out what type to cast it to, if it's not LayerView):

var view = (LayerView)ctor.Invoke(null);
view.Show();

http://msdn.microsoft.com/en-us/library/6ycw1y17.aspx

The Invoke method of ConstructorInfo returns an object reference, so you have to cast it to the type you're expecting.

0

精彩评论

暂无评论...
验证码 换一张
取 消