Below is a simple method I wrote (extremely simplified down so I hope it still gets the jist across) for taking a string representation of an array's elements in a string, and converting them into an actual array of those values. t is the type of the array.
DeserializeArray(string sArrayElements, out Array aValues, Type t)
{
string[] sValues = ProcessArrayElements(sArrayAsString);
ArrayList alValues = new ArrayList(sValues.Length);
for(int i = 0; i < sValues.Length; ++i)
alValues.Add(ProcessValue(sValues[ i ] ));
aValues = alValues.ToArray(t.GetElementType());
return true;
}
I would then use this method with the code below. propertyInfo is the property of an object that in this case .IsArray() == true. sArrayElements is just the string that contains the string representation of the array ("val1,val2,...,valN")
Array aValues;
if (DeserializeArray(sArrayElements, out aValues, propertyInfo.PropertyType))
propertyInfo.SetValue(oObject, aValues, null);
else
throw new FormatException("Unable to parse Array Elements: " + sArrayElements);
This works beautifully in .NET, but not in Silverlight because the ArrayList object is marked as Internal or something (can not use type because access level blah blah blah).
So I am looking for an alternative to the ArrayList.ToArray(Type). I can not just use a List<object>.ToArray() because the PropertyInfo.SetValue() call will bawk at trying to make an object[] into an Int32[] or the like.
I have tried in the DeserializeArray() method to do something like aValues = Array.CreateInstance(t.GetElementType()) but I can not use [] to assign the values and you can not assign values to the foreach(obj in objects).
I then tried changing the aValues parameter to a generic object[] array but i get the same conversion (boxing/unboxing) errors at run time when calling the Array.CreateInstance().
So yeah; I am trying to find a solution to this problem for Silverlight 4. Any help would be greatly appreciated :)
Not tested, but I think this should do what you want:
DeserializeArray(string sArrayElements, out Array aValues, Type t)
{
string[] sValues = ProcessArrayElements(sArrayAsString);
aValues = new Array[sValues.Length];
for(int i = 0; i < sValues.Length; ++i)
aValues.SetValue(Activator.CreateInstance(t,ProcessValue(sValues[i])),i);
return true;
}
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