简体   繁体   中英

How to I pass an object obtained through reflection to a template?

So I need to get a class using reflection, because it is a private class and it's the only way I can think of to create on object of that type. Then I need to pass that object off to template class. I cannot figure out how to create the template class though.

For Example:

Type privateClassType = (Assembly.LoadFile(x)).GetType("Namespace.privateClass");
var Object = Activator.CreateInstance(privateClassType);

Now use it in a template class like List

So, how would I instantiate the List since I find no syntax to replace T with privateClassType or any other way since the class is private and I have no access to it.

Any ideas on how I would declare the List to be correct?

First, in C# space, we call them generics and they are VERY different animals from C++ templates.

Second, to close an open generic type (that is, a generic type with type parameters that haven't been specified), use Type.MakeGenericType :

Type openListType = typeof(List<>);
var closedListType = openListType.MakeGenericType(new[] { privateClassType });
object list = Activator.CreateInstance(closedListType);
// list is List<T> where typeof(T) == privateClassType

Third, it smells bad that you are creating instances of a private class. They are private for a reason.

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