简体   繁体   中英

Cast type which i don't know yet what is it

let's say i have list with properties like this:

Type ArrayType
String Value 

i've got another list like this:

ArrayType=System.Int32
Value=44
Index=0

ArrayType=System.Int32
Value=11
Index=3

ArrayType=System.Int32
Value=7
Index=2

ArrayType=System.Int32
Value=5
Index=1

All values are in string ! I don't know what type will be it, int32 is only example. there will also be floats, strings, etc.

so... i'm creating new array of type which i readed from "ArrayType" property

dynamic newArray = Array.CreateInstance(typeOfArray, arraySize);

I know arraySize of coure

and the Arrays are created properly. But now i want to copy all values (which are in string) to my new array: but i have no idea how to cast it. i've tried something like this:

newArray.SetValue(element.Property.Value,element.Index);

it throw an exception that he can't write OBJECT to my array of ints

so then i've tried to cast in somehow:

 newArray[element.Index] = Convert.ChangeType(element.Property.Value,element.Property.Type); 

but it still can't cast the object

can someone help :) ?

I just made this code example:

var types = new[] { typeof(int), typeof(float), typeof(double) };
var elements = Enumerable.Range(1, 100)
                       .Select((value, index) => new Element(types[index % types.Length], value.ToString(), index));

var integers = elements.Where(element => element.ArrayType == typeof(int));
var array = Array.CreateInstance(typeof(int), 100);

Console.WriteLine(array.GetType());

foreach(var element in integers)
{
    var value = Convert.ChangeType(element.Value, element.ArrayType);
    array.SetValue(value, element.Index);
}

foreach(var value in array)
{
    Console.WriteLine(value + " " + value.GetType());
}

Element class:

public class Element
{
    public Type ArrayType { get; private set; }
    public string Value { get; private set; }
    public int Index { get; private set; }

    public Element(Type type, string value, int index)
    {
        ArrayType = type;
        Value = value;
        Index = index;
    }
}

Which just works

Ok, now all works :D thanks for help!

   foreach (var element in groupedElement)
                {
                    var newInstance = Activator.CreateInstance(element.Property.Type);

                    newInstance = element.Property.Value;

                    newArray.SetValue(Convert.ChangeType(newInstance, element.Property.Type, CultureInfo.InvariantCulture), element.Index);
                }

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