I'm calling a static method on an object using reflection:
MyType.GetMethod("MyMethod", BindingFlags.Static).Invoke(null, new object[] { Parameter1, Parameter2 });
How do you pass parameters by ref, rather that by value? I assume they would be by value by default. The first parameter ("Parameter1" in the array) should be by ref, but I can't figure out how to pass it that way.
13.5.It shall be illegal to use argument passing by reference for subroutines with a lifetime of static.
A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.
Invoke(Object, Object[]) Invokes the method or constructor represented by the current instance, using the specified parameters. Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)
The ref Modifier By default, a reference type passed into a method will have any changes made to its values reflected outside the method as well. If you assign the reference type to a new reference type inside the method, those changes will only be local to the method.
For a reference parameter (or out in C#), reflection will copy the new value into the object array at the same position as the original parameter. You can access that value to see the changed reference.
public class Example {
public static void Foo(ref string name) {
name = "foo";
}
public static void Test() {
var p = new object[1];
var info = typeof(Example).GetMethod("Foo");
info.Invoke(null, p);
var returned = (string)(p[0]); // will be "foo"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With