开发者

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

开发者 https://www.devze.com 2023-03-16 22:56 出处:网络
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.

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 t开发者_运维知识库emplate 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消