【问题标题】:Creating a class with CodeTypeDeclaration and adding members to it使用 CodeTypeDeclaration 创建一个类并向其添加成员
【发布时间】:2013-03-21 12:27:31
【问题描述】:

我在 CodeTypeDeclaration 的帮助下声明一个类,如下所示:

CodeTypeDeclaration targetClass = new CodeTypeDeclaration(sType);

我可以添加一个构造函数:

 CodeConstructor constructor = new CodeConstructor();
 constructor.Attributes = MemberAttributes.Public;

或成员字段:

 CodeMemberField myField = new CodeMemberField();
 myField.Name = fieldName;
 myField.Type = new CodeTypeReference(fieldType);

 targetClass.Members.Add(myField);

但我正在尝试添加任何类型的行,例如常量声明:

const addressFilteresErrorCounters: UInt32 = 0x0000AE77;

我可以在不使用 CodeMemberField 的情况下执行此操作吗? 也许我可以以某种方式向类添加 CodeSnippetStatement,所以我们简单地说,通过使用力向类添加一些行而不是使用 CodeMemberField 过滤声明行?

也许是这样的:

    targetClass.Members.Add(new CodeSnippetStatement("var n = 2"));

谢谢。

【问题讨论】:

  • 嗯,使用sn-p的代码行吗?
  • 不,这只是简单添加的示例。我做不到,所以现在我打开文件并手动添加所需的行。

标签: c# codedom jscript.net


【解决方案1】:

您不能将CodeSnippetStatement 直接添加到课程中。但是,您可以将它们添加到 CodeMemberMethod,例如:

CodeMemberMethod method = new CodeMemberMethod();
method.Name = "DoSomething";
method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
method.Statements.Add(new CodeSnippetStatement("var n = 2;"));

虽然您不需要借助 CodeSnippetStatement 来添加常量。您可以使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-30
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 2021-08-22
    • 2014-05-22
    相关资源
    最近更新 更多