简体   繁体   中英

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.

Reflection works for this purpose

public static T GenerateNewInstance<T>(T obj) where T : class
{
    Type type = typeof (T);
    object instance = Activator.CreateInstance(type);
    return instance as T;
}

I think what you're having trouble with is accessing the object properties (prop?) The compiler doesn't know what specific object type you're working with as it's being cast as an object.

You could make that work runtime using something like:

obj.GetType().GetRuntimeProperty("PropertyName").GetValue(obj);

But ultimately it's a matter of casting the object to a specific class:

class obj = (class)obj;
list.Add(obj.property.ToString());

Edit: I might not understand your question correctly. It also seems like you want to pass different type's. Does the original classes have identical properties or do you just want to add all the properties from a given object into the list?

If they have identical properties, consider creating an interface with those properties and make your classes implement it, that way you can create a new instance of the objects and cast it as the interface and thereby get the properties they share.

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