简体   繁体   English

如何使用CodeDOM创建泛型类,其通用参数是我创建的类型?

[英]How to create a generic class using CodeDOM whose generic parameter is a type that I created?

I have a class that I created using CodeDOM: 我有一个使用CodeDOM创建的类:

CodeTypeDeclaration some_class = new CodeTypeDeclaration("SomeClass");
// ... properties and methods creation elided

I want to create a List of the "SomeClass" type. 我想创建“ SomeClass”类型的列表。 However, I can't seem to do so: 但是,我似乎无法这样做:

var list_type = new CodeTypeReference(typeof (List<>).Name, ??? some_class ???);
var member_field = new CodeMemberField(list_type, field_name)
                                      {
                                               Attributes = MemberAttributes.Private,
                                      }; 

CodeTypeReference doesn't accept a CodeTypeDeclaration , which is what I need. CodeTypeReference不接受CodeTypeDeclaration ,这是我需要的。 What can I do? 我能做什么? I don't want to pass the class name as a string, since this could lead to errors. 不想把类的字符串名字,因为这可能会导致错误。

I'm afraid you can't. 恐怕你做不到。 There doesn't seem to be any way to create a CodeTypeReference from a CodeTypeDeclaration . 似乎没有要任何方式来创建一个CodeTypeReferenceCodeTypeDeclaration I think that's because CodeTypeDeclaration does not know what namespace it's in, so there is no safe way to do that. 认为这是因为CodeTypeDeclaration不知道它在哪个命名空间中,所以没有安全的方法可以做到这一点。

On the other hand, when creating a CodeTypeReference to generic type, you don't need to use the name of the generic type: 另一方面,在创建泛型类型的CodeTypeReference时,您无需使用泛型的名称:

var listType = new CodeTypeReference(typeof(List<>));
listType.TypeArguments.Add(typeof(int));

The chosen answer didn't work for me for whatever reason, but this did: 无论出于何种原因,选择的答案都不适用于我,但这确实可行:

var listType = new CodeTypeReference("List", new[] { new CodeTypeReference(typeof(int)) });

See documentation here. 请参阅此处的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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