【问题标题】:using type returned by Type.GetType() in c#在 c# 中使用 Type.GetType() 返回的类型
【发布时间】:2009-05-27 08:26:28
【问题描述】:

我有一个关于这怎么可能的问题(如果可能的话:) 例如,使用 Type.GetType() 返回的类型引用来创建该类型的 IList?

这里是示例代码:

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

提前谢谢你!

【问题讨论】:

  • IList 是一个接口,所以你不能新建它。您需要新建一个实现 IList 的类型,例如 List.

标签: c# generics reflection


【解决方案1】:

类似这样的:

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

当然不能声明为

IList<customer>

因为它没有在编译时定义。但是List&lt;T&gt;实现了IList,所以你可以使用它。

【讨论】:

  • 是的,因为它不是在编译时定义的,所以使用泛型 List 没有多大意义 - 您还不如使用非泛型容器,例如 ArrayList。
  • 其实你应该把Activator.CreateInstance的结果转换成IList,因为它返回一个对象...
  • @Thomas:谢谢,已修复。 @Groky:这取决于。使用通用列表,您可以在添加项目时进行运行时类型检查。或者您需要将其分配给您知道(通过某些上下文)它属于同一类型的字段。
【解决方案2】:

我最近遇到了这个问题..我意识到这是一个老问题,但认为有人可能会发现我找到的解决方案有用(使用 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);
}

希望我没有让这一切变得混乱,它实际上有所帮助,同时,对于文字墙感到抱歉

【讨论】:

    【解决方案3】:

    Stefan 已经为您的问题提供了解决方案。

    你不能做IList&lt;customer&gt;的原因是你不能以这种方式混合编译时和运行时类型。 当我试图推理这样的事情时,一个提示是:智能感知如何找出它必须显示的成员。在您的示例中,这只能在运行时解决。

    Stefan 给出的答案,可以使用。但是我认为它对你的潜在问题没有帮助,因为它不会给你智能。所以我认为你比只使用非通用列表没有优势。

    【讨论】:

    • 正如 Stefan 在 cmets 中为他的回答指出的那样,仍然有一些优点,例如通用列表阻止代码将不同类型的对象添加到列表中。不过你确实会失去智能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2011-04-16
    相关资源
    最近更新 更多