Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MethodInfo.Invoke with out Parameter

Tags:

c#

an example code what I try to do will surely do better than my english:

public bool IsNumericValueInBounds (string value, Type numericType) {   double d = double.NaN;         bool inBounds = (bool)numericType.GetMethod ("TryParse").Invoke (null, new object[] { value, d });    return inBounds; } 

Unfortunately the TryParse method needs an out parameter so this doesn't work. any ideas how to solve this?

(ps.: would'nt this be a nice example for duck typing? - because i know every numericType has an "TryParse" or I am mistaken?)

like image 713
Bluenuance Avatar asked Feb 20 '09 11:02

Bluenuance


People also ask

How do you call MethodInfo?

To invoke a static method using its MethodInfo object, pass null for obj . If this method overload is used to invoke an instance constructor, the object supplied for obj is reinitialized; that is, all instance initializers are executed. The return value is null .

Can out parameter be optional?

When a method with an omitted optional parameter is called, a stack frame containing the values of all the parameters is created, and the missing value(s) are simply filled with the specified default values. However, an "out" parameter is a reference, not a value.

How do you call a method using parameters?

There are two ways to call a method with parameters in java: Passing parameters of primtive data type and Passing parameters of reference data type. 4. in Java, Everything is passed by value whether it is reference data type or primitive data type.


1 Answers

public static bool TryParse( string text, out int number ) { .. }  MethodInfo method = GetTryParseMethodInfo(); object[] parameters = new object[]{ "12345", null } object result = method.Invoke( null, parameters ); bool blResult = (bool)result; if ( blResult ) {     int parsedNumber = (int)parameters[1]; } 
like image 115
TcKs Avatar answered Oct 26 '22 23:10

TcKs