I want to create a function to dynamic allocate array member element. The array's sizes are different and they get from a file. I use reflection to get array member element from struct object and assign it with the new array created from Array.CreateInstance() function.
private static void initArray<T>(ref T item, BinaryReader br){
var fields = item.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
//....
// get array field from object
//...
arrayType = arrayFieldInfo.FiledType;
int length = br.ReadInt32();
Array arr = Activator.CreateInstance(arrayType, length) as Array;
arrayFieldInfo.SetValue(item, arr); // this code not work
}
I found that the function not work because of this error: error CS0266: Cannot implicitly convert type 'System.Array'. Please help me.
---updated---- I put the sample code here
struct Person
{
public Address[] addresses;
}
struct Address
{
public int nCode;
public string homeAddress;
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
int nSize = 100;//hard code instead of read from file
var fields = typeof(Person).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
foreach (var fieldInfo in fields)
{
if (fieldInfo.FieldType.IsArray)
{
Array arr = Array.CreateInstance(fieldInfo.FieldType.GetElementType(), nSize);
//1. Using reflection to set value
fieldInfo.SetValue(p, arr);
if(p.addresses == null)
{
Console.WriteLine("Reflection-Not success");
}
else
{
Console.WriteLine("Reflection-success");
}
//2. Using assignment operator with explicit cast
p.addresses = (Address[])arr;
if (p.addresses == null)
{
Console.WriteLine("cast-Not success");
}
else
{
Console.WriteLine("cast-Success!!");
}
}
}
}
}