【问题标题】:CodeDom How to create a method with void return type?CodeDom 如何创建一个返回类型为 void 的方法?
【发布时间】:2016-11-28 11:46:11
【问题描述】:
public void CreateMethod()
{
    CodeMemberMethod mymethod = new CodeMemberMethod();
    mymethod.Name = testMethod;
    CodeTypeReference ctr = new CodeTypeReference();
    //Assign the return type to the method.
    mymethod.ReturnType = ctr;

    CodeSnippetExpression snippet1 = new CodeSnippetExpression("AutomationBase obj = new AutomationBase()");
    CodeSnippetExpression snippet2 = new CodeSnippetExpression("obj.Execute(testCases[1])");       
    CodeExpressionStatement stmt1 = new CodeExpressionStatement(snippet1);
    CodeExpressionStatement stmt2 = new CodeExpressionStatement(snippet2);
    mymethod.Statements.Add(stmt1);
    mymethod.Statements.Add(stmt2);
    mymethod.Attributes = MemberAttributes.Public;
    myclass.Members.Add(mymethod);
}

输出

 public virtual void TestCaseId002() {
            AutomationBase obj = new AutomationBase();
            obj.Execute(testCases[1]);
        }

得到虚空

我只需要 void。

【问题讨论】:

  • virtual 与返回类型无关。
  • 由于ctr.;,您提供的代码甚至无法编译。请提供minimal reproducible example(也不清楚这与 ASP.NET 有什么关系……)
  • 但默认情况下 c# 方法是非虚拟的。
  • @jon 它只是一个编辑更改
  • 但 CodeDom(尝试)与语言无关。仅仅因为 C# 有一定的规则,并不代表 CodeDom 有。

标签: c# asp.net .net code-generation codedom


【解决方案1】:

您需要将该方法标记为Final,以表明它不可继承:

mymethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;

【讨论】:

  • 我还有一个疑问,我们如何指定需要生成代码的位置?
猜你喜欢
  • 1970-01-01
  • 2012-05-03
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多