Using PrivateObject.Invoke to call a static conversion function do not compile in C#
-
27-03-2021 - |
Question
I have a test method where I call an private function that converts a kind of to another kind.
This static function have the following signature:
private static Destiny[] Array2Array<Origin,Destiny> (Origin[] OriginVector)
Since it's a private function, the tester give an error saying it cannot access it. So I got to this point:
Origin[] OriginVector = null; // TODO: Initialize to an appropriate value
Destiny[] expected = null; // TODO: Initialize to an appropriate value
Destiny[] actual;
var dummy = new ConversionClass();
var po = new PrivateObject( dummy, new PrivateType(typeof(ConversionClass)));
var acessor = new ConversionClassAcessor(po);
actual = po.Invoke("Array2Array",
new [] { typeof(Origin[]), typeof(Destiny[]) },
new object[] { OriginVector } );
EDIT: That last line throws an compiler error with the message "cannot convert type object to Destiny[]". What I'm doing wrong?
Solution
The answer is simple.. cast it. :D
actual = (Destiny[]) po.Invoke("Array2Array",
new [] { typeof(Origin[]), typeof(Destiny[]) },
new object[] { OriginVector } );
OTHER TIPS
Mr Chris Shain,
I will here reproduce the solution you gave me. Since you deleted your answer, if you add a new one after this, I'll delete this and accept yours as the question's answer.
The problem with the code above is that actual
variable is of type Destiny[]
and the result of Invoke is System.Object. An typecast is needed:
actual = (Destiny[]) po.Invoke("Array2Array",
new [] { typeof(Origin[]), typeof(Destiny[]) },
new object[] { OriginVector } );