为了历史。显然,没有通用的方法来使用 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 代码与使用 is 和 as 运算符时生成的代码不同。但在这种情况下,目标语言可以是任何语言。