在实例化从泛型继承的类型时,有没有办法不使用动态? [英] Is there a way not to use dynamic when instantiating a type that inherits from generic?

查看:41
本文介绍了在实例化从泛型继承的类型时,有没有办法不使用动态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I create an instance a type that inherits from generic, and statically cast it to its base type

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)

推荐答案

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

Normally the way to do that is to include a non-generic API in there (perhaps with explicit implementation). Then you just cast to the non-generic interface.

不完全一样,但有点像:

Not quite the same, but a bit like:

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

这篇关于在实例化从泛型继承的类型时,有没有办法不使用动态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆