C# 在c中使用type.GetType()返回的类型#
我有一个关于如何可能的问题(如果可能的话:) 例如,使用type.GetType()返回的类型引用来创建该类型的IList 下面是示例代码:C# 在c中使用type.GetType()返回的类型#,c#,generics,reflection,C#,Generics,Reflection,我有一个关于如何可能的问题(如果可能的话:) 例如,使用type.GetType()返回的类型引用来创建该类型的IList 下面是示例代码: Type customer = Type.GetType("myapp.Customer"); IList<customer> customerList = new List<customer>(); // got an error here =[ Type customer=Type.GetType(“myapp.custome
Type customer = Type.GetType("myapp.Customer");
IList<customer> customerList = new List<customer>(); // got an error here =[
Type customer=Type.GetType(“myapp.customer”);
IList customerList=新列表();//这里有个错误=[
提前谢谢!类似这样的内容:
Type listType = typeof(List<>).MakeGenericType(customer);
IList customerList = (IList)Activator.CreateInstance(listType);
Type listType=typeof(列表)。MakeGenericType(客户);
IList customerList=(IList)Activator.CreateInstance(listType);
当然你不能把它声明为
IList<customer>
IList
因为它不是在编译时定义的。但是
List
实现了IList,所以您可以使用它。您的问题的解决方案已经由Stefan提供了
不能执行IList的原因是不能以这种方式混合编译时和运行时类型。
当我试图对这样的事情进行推理时,一个提示是:intellisense如何确定它必须显示哪些成员。在您的示例中,这只能在运行时解决
Stefan给出的答案是可以使用的。但是我认为它对你的潜在问题没有帮助,因为它没有给你智能感。因此我认为你没有比只使用非通用列表更大的优势。我最近遇到了这个问题。。我意识到这是一个老问题,但我认为有人可能会找到有用的解决方案(使用NET4.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...
}
希望我没有把它弄得很混乱,它实际上是有帮助的,而且,很抱歉,IList是一个界面,所以你不能新建它。你需要新建一个实现IList的类型,比如List。是的,因为它不是在编译时定义的,所以使用泛型列表没有多大意义-你也可以使用一个非泛型容器,比如s ArrayList。实际上,您应该将Activator.CreateInstance的结果强制转换为IList,因为它返回一个对象…@Thomas:谢谢,修复了它。@Groky:这取决于情况。使用泛型列表,您可以在添加项时进行运行时类型检查。或者您需要将其分配给您知道的字段(通过某些上下文)它是同一类型的。正如Stefan在回答的评论中指出的那样,仍然有一些优点,例如泛型列表阻止代码向列表中添加不同类型的对象。但是,您确实会失去intellisense。
public void myMethod( ISomeInterface param ) {
dynamic value = Factory.GetRealType ( param );
DoSomething(value);
}