473,800 Members | 2,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

invoke methods with params

Hi
I want to use reflection to call a method which accepts "params
string[]" as an argument

I've searched this group and found a better idea than invoke, just
cast to an interface and then call the method
directly, but I would still like to know if this is possible, e.g.
something like the below

ta
C


public class TestA
{
public void Meth(params string[] args)
{
}
}

public partial class _Default : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{
Type handlerInvoke = Type.GetType("R eflectionProjec t.TestA");
object targetToInvoke = Activator.Creat eInstance(handl erInvoke);

MethodInfo methodToInvoke = handlerInvoke.G etMethod("Meth" ,
BindingFlags.In stance | BindingFlags.Pu blic);

string[] myArgs = {"a", "b", "c"};

if (methodToInvoke != null)
{
try
{

object[] args = new object[myArgs.Length];
for (int i = 0; i < myArgs.Length; i++)
{
args[i] = myArgs[i];
}
//object[] args = myArgs;

bool invokeResult = (bool)methodToI nvoke.Invoke(ta rgetToInvoke,
args);
}
catch (Exception la)
{
int a = 0; a++;
}
}
}
Jun 27 '08 #1
7 5432
Yes it is possible, but you need to double-wrap the args - i.e. you
need:

string[] paramsArgs = {...blah...}

object[] methodArgs = {paramsArgs};

That way, it (correctly) treats it as a single argument that is an
array, rather than "n" arguments.

Marc
Jun 27 '08 #2
Like so:

using System;
using System.Reflecti on;

static class Program
{
static void Main()
{
MethodInfo method = typeof(Program) .GetMethod("Tes t");
string[] values = { "foo", "bar" };
object[] args = { values };
method.Invoke(n ull, args);
}
public static void Test(params string[] values)
{
foreach (string val in values)
{
Console.WriteLi ne(val);
}
}
}

Jun 27 '08 #3
<co**********@g ooglemail.comwr ote:
I want to use reflection to call a method which accepts "params
string[]" as an argument

I've searched this group and found a better idea than invoke, just
cast to an interface and then call the method
directly, but I would still like to know if this is possible, e.g.
something like the below
Sort of - but you've got it slightly wrong. You're trying to invoke a
method with several string parameters, instead of with a single string
array parameter.

Try:

object[] args = new object[] { myArgs };
--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jun 27 '08 #4
I did try this, I get an "object reference not set" exception, i.e.

namespace ReflectionProje ct
{

public class TestA
{
public void Meth(params string[] args)
{
}
}

public partial class _Default : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{
Type handlerInvoke = Type.GetType("R eflectionProjec t.TestA");
object targetToInvoke = Activator.Creat eInstance(handl erInvoke);

MethodInfo methodToInvoke = handlerInvoke.G etMethod("Meth" ,
BindingFlags.In stance | BindingFlags.Pu blic);

string[] myArgs = {"a", "b", "c"};

if (methodToInvoke != null)
{
try
{

object[] args = { myArgs };
bool invokeResult = (bool)methodToI nvoke.Invoke(ta rgetToInvoke,
args);
}
catch (Exception la)
{
int a = 0; a++;
}
}
}
}
}
Jun 27 '08 #5
The error is because you are trying to cast the result of a "void"
method to bool. Either ignore the result, or make the method return a
bool.

Marc
Jun 27 '08 #6
<co**********@g ooglemail.comwr ote:
I did try this, I get an "object reference not set" exception, i.e.
Well, it would really help if you'd give a short but complete example
which *doesn't* need to be run in ASP.NET...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jun 27 '08 #7
On 23 Apr, 21:48, Marc Gravell <marc.grav...@g mail.comwrote:
The error is because you are trying to cast the result of a "void"
method to bool. Either ignore the result, or make the method return a
bool.

Marc
Doh! Your quite right, thats a result of trying many things over time
and then dozily not noticing. Works now, thanks.

Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1594
by: RickDee | last post by:
Hi. I need help badly here. I need to write a program to invoke methods ( static, public, nonstatic, with parameters, and etc ) from an exe file, but I keep facing problem. From all the notes that I read from internet, I realized that InvokeMember works for methods in class, but not when I have an exe ( right ?). My program looks like this :
5
4313
by: RickDee | last post by:
Please help, anybody. I am trying to write a program so that it can launch an exe file ( which is also genereated in C# ) and then simulate the button clicking and invoke the methods inside the exe. The button clicking part is working fine, but I just cannot get the method call. Here is my program snippet. **************************************************************
8
1653
by: WakeBdr | last post by:
I'm writing a class that will query a database for some data and return the result to the caller. I need to be able to return the result of the query in several different ways: list, xml, dictionary, etc. I was wondering if I can use decorators to accomplish this. For instance, I have the following method def getUsers(self, params): return users.query(dbc)
1
4454
by: =?iso-8859-1?B?S2VyZW0gR/xtcvxrY/w=?= | last post by:
Hi, can someone please tell me why the **** this does not work as expected: First at all, thats what a WMI parameter looks like: public class WMIParameter {
0
9550
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10501
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10273
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10250
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10032
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7574
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.