mardi 13 octobre 2015

Instantiating Object in a method from Type passed as parameter

I'm trying to pass a Type to a method and have it instantiate an Object of said Type. I have a lot of repeated code which resembles:

foreach (Link link in links)
{
    Object obj = new Object(link);
    list.Add("Description" + obj.prop.ToString());
}

With numerous different classes/objects.

I envision:

private void populateList(List<Link> links, Type type, List<val> list, string desc)
{
    foreach (Link link in links)
    {
        //Instantiate Object from type parameter here?
        list.Add(desc + obj.prop.ToString());
    }
}

I attempted to use Generics and Reflection to solve the problem:

Type[] typeArgs = {typeof(Link)};
Type constructed = type.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);

But I wasn't too sure where to go next as I'm not able to use either o or constructed to do what I need.

I'm a complete beginner with Reflection and Generics so I'm not even sure if what I'm asking is possible. I'd appreciate any advice on where to go next or any potential solutions.





Aucun commentaire:

Enregistrer un commentaire