简体   繁体   中英

Casting system.array to object in c#

my function has the following signature

function myfunction(ref object)

I use it as such

 Array arr = Array.CreateInstance(System.Type.GetType("System.String"), 2);
  arr.SetValue("1", 0);

  myfunction( ref arr);

And I am getting

"cannot convert from 'ref System.Array' to 'ref object'"

I was under the impression that System.Array is object ...so why am I getting this error? Is object different from Object?

The problem you're having is that while an array is an object, an object is not an array, so in your function, if your array could be passed in as a ref object, the array could be assigned anything that is an object.

Edit:

To fix this problem declare a ref variable to use in place of the array variable:

Array arr = Array.CreateInstance(System.Type.GetType("System.String"), 2);
arr.SetValue("1", 0);

object referenceObject = arr;

myfunction( ref referenceObject );

Think of 'ref object' as "I take a reference to a variable that can store an Object". Suppose that 'myfunction' tried to store an 'int' to the variable you passed? This would fail at runtime, which is undesirable.

On a side note, you can use typeof(string) in place of calling GetType("System.String"). You can also just say:

Object arr = new string[2];

To access the array first, you can do this:

string[] arr = new string[2];
arr[0] = "1";
object arrObj = arr;
myfunction(ref arrObj);

I would double check that you're using the method myfunction correctly; it's a rather unusual parameter type for taking an initialized array.

Declare the variable as object and not as array. To populate the array with values you should keep your array variable and declare another one to give it to the method.

Array myArray = ....;
Object myObject = myArray;
myFunction(ref myObject);

// Update the original reference
myArray = myObject as Array;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM