This would be pretty straight forward if I knew the types at compile time or if it was a generic parameter, because I could do something like myArray.Cast<T>()
But what I actually have is essentially this. I do not have a known type or generic parameter. I have a System.Type
variable.
// could actually be anything else
Type myType = typeof(string);
// i already know all the elements are the correct types
object[] myArray = new object[] { "foo", "bar" };
Is there some kind of reflection magic I can do to get a string[]
reference containing the same data? (where string
isn't known at compile time)
Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .
Core Java bootcamp program with Hands on practicetoArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.
Using numpy.asarray() , and true (by default) in the case of np. array() . This means that np. array() will make a copy of the object (by default) and convert that to an array, while np.
1 Answer. Explanation: singletonList() returns the object as an immutable List. This is an easy way to convert a single object into a list. This was added by Java 2.0.
It's not really a cast as such (I'm allocating a new array and copying the original), but maybe this can help you out?
Type myType = typeof(string);
object[] myArray = new object[] { "foo", "bar" };
Array destinationArray = Array.CreateInstance(myType, myArray.Length);
Array.Copy(myArray, destinationArray, myArray.Length);
In this code, destinationArray
will be an instance of string[]
(or an array of whatever type myType
was).
You can't perform such a cast, because the arrays object[] and string[] are actually different types and are not convertible. However, if you wanted to pass different such types to a function, just make the parameter IEnumerable. You can then pass an array of any type, list of any type, etc.
// Make an array from any IEnumerable (array, list, etc.)
Array MakeArray(IEnumerable parm, Type t)
{
if (parm == null)
return Array.CreateInstance(t, 0);
int arrCount;
if (parm is IList) // Most arrays etc. implement IList
arrCount = ((IList)parm).Count;
else
{
arrCount = 0;
foreach (object nextMember in parm)
{
if (nextMember.GetType() == t)
++arrCount;
}
}
Array retval = Array.CreateInstance(t, arrCount);
int ix = 0;
foreach (object nextMember in parm)
{
if (nextMember.GetType() == t)
retval.SetValue(nextMember, ix);
++ix;
}
return retval;
}
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