简体   繁体   中英

Using a type obtained through reflection in a data structure?

I have a class FutureClass that exists in .NET 4.6, but I'd like to be able to use it in an older codebase that builds with .NET 4.0. I can obtain and call FutureClass objects, but I want to store them in, say, a Dictionary<string, FutureClass> .

I've tried the following:

Dictionary<string, FutureClass> dict = new Dictionary<string, FutureClass>(); // didn't expect it to work

and

Type futureClassType = [...] //dynamically load the type from the assembly compiled with .NET 4.6
Dictionary<string, futureClassType> dict = new Dictionary<string, futureClassType>(); // held some promise, I thought

Is there a way to do what I'm trying? Thanks!

As far as static typing your dictionary variable, I think you're limited to one of two options -- either use a Dictionary<string, object> or a Dictionary<string, dynamic> .

Otherwise, you could do something like this:

Type futureClassType = ...;
var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), futureClassType);
var dictionary = Activator.CreateInstance(dictionaryType);

But here, the resulting dictionary variable is of type object. You could cast it to a non-generic IDictionary , ICollection or IEnumerable , but you can't cast it to a generic form of any of the above.

Loading the type at runtime has some severe handicaps like the one you just encountered. You cannot use the type in compile-time expressions like using it as a generic type parameter.

Your only option will be to copy the class over to your own codebase, which should not be too difficult because the .NET framework is officially open source now. The only trouble you might run in to is that the class has many .NET >= 4.5 dependencies, possibly recursively.

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