【问题标题】:C# CodeDom "as" and "is" keywords functionalityC# CodeDom“as”和“is”关键字功能
【发布时间】:2018-09-04 13:27:29
【问题描述】:

使用 CodeDom 我正在寻找一种方法来生成这样的 c# 代码:

SomeRefType typedVar = obj as SomeRefType;

或者这个:

Boolean result = obj is SomeRefType;

但到目前为止,我发现的只是CodeCastExpression 类,它可以生成显式类型转换。但这不是我需要的。 有没有办法使用 CodeDom 实现“as”和“is”关键字功能?

【问题讨论】:

  • 哦。看来“运营商”这个词起了作用。我会检查它...

标签: c# type-conversion code-generation codedom


【解决方案1】:

为了历史。显然,没有通用的方法来使用 CodeDom 模型来实现这些运算符。

可以使用 CodeSnippetExpression 生成必要的代码。但解决方案取决于所使用的目标语言。

statements.Add(new CodeVariableDeclarationStatement("SomeRefType", "typedVar", new CodeSnippetExpression("obj as SomeRefType")));
statements.Add(new CodeVariableDeclarationStatement("Boolean", "result", new CodeSnippetExpression("obj is SomeRefType")));

另一种选择是用实际上相似的逻辑替换这些运算符。所以对于is 运算符,代码是这样的:

statements.Add(new CodeVariableDeclarationStatement("Boolean", "result", new CodeMethodInvokeExpression(new CodeTypeOfExpression("SomeRefType"), "IsInstanceOfType", new CodeVariableReferenceExpression("obj"))));
// Boolean result = typeof(SomeRefType).IsInstanceOfType(obj);

对于as 这样的操作员:

statements.Add(new CodeVariableDeclarationStatement("SomeRefType", "typedVal"));
statements.Add(new CodeConditionStatement(
    new CodeMethodInvokeExpression(new CodeTypeOfExpression("SomeRefType"), "IsInstanceOfType", new CodeVariableReferenceExpression("obj")),
    new CodeStatement[] { 
        new CodeAssignStatement(new CodeVariableReferenceExpression("typedVal"), new CodeCastExpression("SomeRefType", new CodeVariableReferenceExpression("obj")))
    },
    new CodeStatement[] {
        new CodeAssignStatement(new CodeVariableReferenceExpression("typedVal"), new CodePrimitiveExpression(null))
    }));
// SomeRefType typedVal = typeof(SomeRefType).IsInstanceOfType(obj) ? (SomeRefType)obj : null;

生成的 IL 代码与使用 isas 运算符时生成的代码不同。但在这种情况下,目标语言可以是任何语言。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2011-01-22
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多