简体   繁体   中英

Reflection form create instance with Generic interface

I have a generic selection for my interface like this:

        public interface IMyInterface{
              void ok();
        }

        var maps = (from t in types
                    from i in t.GetInterfaces()
                    where typeof(IMyInterface).IsAssignableFrom(t) &&
                          !t.IsAbstract &&
                          !t.IsInterface
                    select (IMyInterface)Activator.CreateInstance(t)).ToArray();

But I changed my interface to generic,

        public interface IMyInterface<T>{
              void ok<T>();
        }

        var maps = (from t in types 
                    from i in t.GetInterfaces()
                    where i.IsGenericType 
                        && i.GetGenericTypeDefinition() == typeof(IMyInterface<>)
                        && !t.IsAbstract
                        && !t.IsInterface
                        select ???????????????????????????????
                    ).ToArray();

but now the casting is not working.

        select (IMyInterface<>)Activator.CreateInstance(t)).ToArray();

Gives build error for casting.

IMyInterface<T> is not a IMyInterface<> , therefore the cast is not valid. The compiler just protects you from finding this at runtime, because you can never have a value of type GenericType<> in C# - non-reified generic types are only used for reflection.

Note how typeof(IMyInterface<>).IsAssignableFrom(typeof(IMyInterface<string>)) returns false . The two types are completely different and only share a common generic definition, the same as List<int> and List<string> are two different types that only share a common generic definition. C# generics aren't Java generics.

There is no common type you can use to encompass both List<string> and List<int> , just like there's not common type you can use for your IMyInterface<A> and IMyInterface<B> . Either make sure everything is properly generic, or make another interface that isn't generic and that IMyInterface<T> implements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM