简体   繁体   English

C# CodeDom "as" 和 "is" 关键字功能

[英]C# CodeDom "as" and "is" keywords functionality

Using CodeDom I'm looking for a way to generate c# code like this:使用 CodeDom 我正在寻找一种生成 c# 代码的方法,如下所示:

SomeRefType typedVar = obj as SomeRefType;

or this:或这个:

Boolean result = obj is SomeRefType;

But as far, all what I've found is CodeCastExpression class which can generate explicit type casting.但到目前为止,我发现的所有内容都是CodeCastExpression类,它可以生成显式类型转换。 But this is not what I need.但这不是我需要的。 Is there any way to implement "as" and "is" keywords functionality using CodeDom?有什么方法可以使用 CodeDom 实现“as”和“is”关键字功能?

For history.对于历史。 Apparently, there's no universal way to implement these operators with CodeDom model.显然,没有使用 CodeDom 模型实现这些运算符的通用方法。

It is possible to use CodeSnippetExpression to generate necessary code.可以使用 CodeSnippetExpression 生成必要的代码。 But the solution becomes dependent on the target language used.但是解决方案取决于所使用的目标语言。

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

Another option is to replace these operators with effectively similar logic.另一种选择是用有效相似的逻辑替换这些运算符。 So for is operator the code is something like that:所以对于is运算符,代码是这样的:

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

and for as opeartor like that:as这样的opeartor:

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;

The generated IL-code is different from the code which is generated when using is and as operators.生成的 IL 代码与使用isas运算符时生成的代码不同。 But in this case the target language can be any.但在这种情况下,目标语言可以是任何语言。

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

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