lundi 22 mai 2017

C# - How can I convert an object to a certain type

I'm trying to convert an object to a certain type and I don't know what that type actually is. I know it's either a primitive type or a string but not much else. And I don't wanna fill my code with a bunch of if's just checking the type. Here's the code

private object  MakeNewArray<TTDest>(object src, PropertyInfo getter) {
        object [] obj = (object[]) getter.GetValue(src);

        TTDest [] ret = new TTDest[obj.Length];
        for (int i = 0; i < obj.Length; i++) {
            ret[i] = (TTDest) obj[i];
        }
        return ret;
    }

And here's the part in the code where I call this method

Type tDest = destType.GetProperty(info.GetDest().Name)?.
PropertyInfo getter = info.GetSrc() as PropertyInfo;
Type elementType = tDest.GetElementType();
return MakeNewArray<elementType>(src, getter);





Aucun commentaire:

Enregistrer un commentaire