使用CodeDom我正在寻找一种生成c#代码的方法,如下所示:
SomeRefType typedVar = obj as SomeRefType;
或这个:
Boolean result = obj is SomeRefType;
但到目前为止,我发现的所有内容都是CodeCastExpression类,它可以生成显式类型转换。但这不是我需要的。有没有办法使用CodeDom实现“as”和“is”关键字功能?
对于历史。显然,没有通用的方法来使用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);
对于像这样的qazxsw poi运营商:
as
生成的IL代码与使用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;
和is
运算符时生成的代码不同。但在这种情况下,目标语言可以是任何语言。