开发者

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 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜