using type returned by Type.GetType() in c#

2019-01-11 11:02发布

问题:

i've got a question about how is it possible (if possible :) to use a type reference returned by Type.GetType() to, for example, create IList of that type?

here's sample code :

Type customer = Type.GetType("myapp.Customer");
IList<customer> customerList = new List<customer>(); // got an error here =[

Thank You in Advance !

回答1:

Something like this:

Type listType = typeof(List<>).MakeGenericType(customer);
IList customerList = (IList)Activator.CreateInstance(listType);

Of course you can't declare it as

IList<customer>

because it is not defined at compile time. But List<T> implements IList, so you can use this.



回答2:

I recently faced this problem..I realize this is an old question, but thought someone might find useful the solution i found (using net 4.0 ). This is the setup i had:

public interface ISomeInterface{
     String GetEntityType{ get; }
}

public abstract class BaseClass : ISomeInterface{
     public String GetEntityType { 
          get{ return this.GetType().ToString(); }
     }
}

public class ChildA : BaseClass {  }

public class ChildB : BaseClass {  }

What I did was create a factory method:

public static dynamic GetRealType { ISomeInterface param } {
     return Activator.CreateInstance("dllname", param.GetEntityType);
}

Creating the object as a dynamic type was what solved it for me. I inferred the type by having a method:

public void DoSomething<T>(T param){

     IList<T> list = somecode...
}

this allowed me to do a call to the method and let .net infer the type

public void myMethod( ISomeInterface param ) {
     dynamic value = Factory.GetRealType ( param );
     DoSomething(value);
}

Hope i didn't make it all confusing and it actually helps, also, sorry for the wall of text



回答3:

The solution to your problem is provided by Stefan already.

The reason that you can not do IList<customer> is because you can not mix compile time and run-time types this way. A hint when I try to reason about something like this is: how can intellisense figure out what members it must show. In your example this can only be resolved at runtime.

The answer given by Stefan, can be used. However I think it does not help in your underlying problem, because it does not give you intellisense. So I think you have no advantage over using just a non-generic list.