【问题标题】:Is there a way not to use dynamic when instantiating a type that inherits from generic?实例化从泛型继承的类型时,有没有办法不使用动态?
【发布时间】:2010-12-15 23:04:10
【问题描述】:

如何创建一个从泛型继承的类型的实例,并将其静态转换为其基类型

foreach(Type t in x.ChildType.Assembly.GetTypes())
{
    if (t.BaseType.IsGenericType)
    {
        if (t.BaseType.GetGenericTypeDefinition() == typeof(ClassMapExt<>)) 
        {
            if (t.BaseType.GetGenericArguments()[0] == x.ChildType) 
            {
                // t is BonusMap. BonusMap is declared as:
                // class BonusMap : ClassMapExt<Bonus>
                dynamic bz = Activator.CreateInstance(t);  

                // the last line is analogous to:
                // var bz = new BonusMap();

                // statically casting it doesn't work
                // var bz = (ClassMapExt<>) Activator.CreateInstance(t); 

                foreach (IManyToOneMappingProvider imt1 in bz.ExtReference)

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    通常的方法是在其中包含一个非泛型 API(可能带有显式实现)。然后你只需转换到非泛型接口。

    不太一样,但有点像:

    Type itemType = ...;
    IList list = (IList)Activator.CreateInstance(
        typeof(List<>).MakeGenericType(itemType));
    list.Add(...);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多