我有一个关于如何(如果可能的话 :) 使用Type.GetType()返回的类型引用来创建该类型的IList的问题?
以下是示例代码:
Type customer = Type.GetType("myapp.Customer");
IList<customer> customerList = new List<customer>(); // got an error here =[
提前感谢您!
我有一个关于如何(如果可能的话 :) 使用Type.GetType()返回的类型引用来创建该类型的IList的问题?
以下是示例代码:
Type customer = Type.GetType("myapp.Customer");
IList<customer> customerList = new List<customer>(); // got an error here =[
提前感谢您!
类似这样:
Type listType = typeof(List<>).MakeGenericType(customer);
IList customerList = (IList)Activator.CreateInstance(listType);
当然你不能将其声明为。IList<customer>
由于它在编译时没有被定义,但 List<T>
实现了 IList 接口,因此您可以使用它。
我最近遇到了这个问题...我意识到这是一个老问题,但是认为有人可能会发现我找到的解决方案很有用(使用net 4.0)。 这就是我的安装设置:
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 { }
public static dynamic GetRealType { ISomeInterface param } {
return Activator.CreateInstance("dllname", param.GetEntityType);
}
public void DoSomething<T>(T param){
IList<T> list = somecode...
}
这使我能够调用该方法并让 .net 推断类型。
public void myMethod( ISomeInterface param ) {
dynamic value = Factory.GetRealType ( param );
DoSomething(value);
}
Stefan已经提供了解决您问题的方案。
您无法使用 IList<customer>
的原因是您不能以这种方式混合编译时和运行时类型。当我尝试推理类似这样的事情时,一个提示是:智能感知如何确定它必须显示哪些成员。在您的示例中,只有在运行时才能解决此问题。
Stefan给出的答案可以使用。但是我认为它对您的根本问题没有帮助,因为它不会给您提供智能感知。因此,我认为您使用非泛型列表没有任何优势。