使用c#中Type.GetType()返回的类型
我有一个问题,如何使用Type.GetType()返回的类型引用(如果可能的话),例如,创建该类型的IList?
这是示例代码:
Type customer = Type.GetType("myapp.Customer"); IList customerList = new List(); // got an error here =[
先感谢您 !
像这样的东西:
Type listType = typeof(List<>).MakeGenericType(customer); IList customerList = (IList)Activator.CreateInstance(listType);
当然你不能声明它
IList
因为它没有在编译时定义。 但是List
实现了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 param){ IList list = somecode... }
这允许我调用方法,让.net推断出类型
public void myMethod( ISomeInterface param ) { dynamic value = Factory.GetRealType ( param ); DoSomething(value); }
希望我没有让这一切变得混乱,它实际上也有助于对文本的墙壁感到抱歉
您的问题的解决方案已由Stefan提供。
你不能做IList
的原因是因为你不能用这种方式混合编译时和运行时类型。 当我尝试推理类似这样的事情时的一个暗示是:intellisense如何确定它必须显示的成员。 在您的示例中,这只能在运行时解决。
可以使用Stefan给出的答案。 但是我觉得它对你的潜在问题没有帮助,因为它没有给你智能感知。 所以我认为你只使用非通用列表没有优势。