[英]Creating a class with CodeTypeDeclaration and adding members to it
i am declaring a class with the help of CodeTypeDeclaration like this : 我在这样的CodeTypeDeclaration的帮助下声明了一个类:
CodeTypeDeclaration targetClass = new CodeTypeDeclaration(sType);
I can add a constructor : 我可以添加一个构造函数:
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public;
Or a member field : 或成员字段:
CodeMemberField myField = new CodeMemberField();
myField.Name = fieldName;
myField.Type = new CodeTypeReference(fieldType);
targetClass.Members.Add(myField);
But i am trying to add any kind of line , for example a constant declaration : 但是我试图添加任何类型的行,例如常量声明:
const addressFilteresErrorCounters: UInt32 = 0x0000AE77;
Can i do this without using CodeMemberField ? 我可以不使用CodeMemberField来做到这一点吗? Maybe somehow i can add to the class a CodeSnippetStatement, so let's simply say , add some line to the class by the using the force and not filtering the declaration line with the CodeMemberField ?
也许我可以以某种方式将CodeSnippetStatement添加到类中,所以简单地说,通过使用强制在类中添加一些行,而不用CodeMemberField过滤声明行?
Maybe smth like this : 也许像这样:
targetClass.Members.Add(new CodeSnippetStatement("var n = 2"));
Thanks. 谢谢。
You can't add a CodeSnippetStatement
directly to a class. 您不能将
CodeSnippetStatement
直接添加到类。 You can, however, add them to a CodeMemberMethod
for example: 但是,您可以将它们添加到
CodeMemberMethod
,例如:
CodeMemberMethod method = new CodeMemberMethod();
method.Name = "DoSomething";
method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
method.Statements.Add(new CodeSnippetStatement("var n = 2;"));
Although you don't need to resort to a CodeSnippetStatement
to add a constant. 尽管您无需
CodeSnippetStatement
来添加常量。 You can use: 您可以使用:
CodeTypeDeclaration exampleClass = new CodeTypeDeclaration("GeneratedClass");
CodeMemberField constant = new CodeMemberField(new CodeTypeReference(typeof(System.UInt32)), "addressFilteresErrorCounters");
constant.Attributes = MemberAttributes.Const;
constant.InitExpression = new CodePrimitiveExpression(0x0000AE77);
exampleClass.Members.Add(constant);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.