Is there a way not to use dynamic when instantiati

2019-07-08 18:35发布

问题:

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)

回答1:

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(...);


标签: c# reflection