本文整理汇总了C#中ExpressionSyntax.CastTo方法的典型用法代码示例。如果您正苦于以下问题:C# ExpressionSyntax.CastTo方法的具体用法?C# ExpressionSyntax.CastTo怎么用?C# ExpressionSyntax.CastTo使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ExpressionSyntax
的用法示例。
在下文中一共展示了ExpressionSyntax.CastTo方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateConditional
protected ExpressionSyntax CreateConditional(ExpressionSyntax whenTrue, ExpressionSyntax whenFalse, ITypeSymbol targetType)
{
Debug.Assert(whenTrue != null);
Debug.Assert(whenTrue.FirstAncestorOrSelf<CompilationUnitSyntax>() == SemanticModel.SyntaxTree.GetRoot());
Debug.Assert(whenFalse != null);
Debug.Assert(whenFalse.FirstAncestorOrSelf<CompilationUnitSyntax>() == SemanticModel.SyntaxTree.GetRoot());
Debug.Assert(targetType != null);
// If there is no conversion between when-true and when-false, we need to insert a cast in
// one or both of the branches.
if (!ConversionExists(whenTrue, whenFalse))
{
var whenTrueConversion = SemanticModel.ClassifyConversion(whenTrue, targetType);
var whenFalseConversion = SemanticModel.ClassifyConversion(whenFalse, targetType);
if (whenTrueConversion.IsExplicit)
{
whenTrue = whenTrue.CastTo(targetType);
}
else if (whenFalseConversion.IsExplicit)
{
whenFalse = whenFalse.CastTo(targetType);
}
else if (whenTrueConversion.IsImplicit && whenFalseConversion.IsImplicit)
{
whenTrue = whenTrue.CastTo(targetType);
}
}
var condition = IfStatement.Condition.Kind() == SyntaxKind.SimpleAssignmentExpression
? IfStatement.Condition.Parenthesize()
: IfStatement.Condition;
ExpressionSyntax result = SyntaxFactory.ConditionalExpression(condition, whenTrue, whenFalse);
// Ensure that the conditional is implicitly convertible to the target type; otherwise,
// insert a cast. We do this be speculatively determining the conversion classification
// of the conditional expression to the target type in the same scope as the original
// if-statement.
var conversion = SemanticModel.ClassifyConversion(IfStatement.Span.Start, result, targetType);
if (conversion.IsExplicit)
{
result = result.CastTo(targetType);
}
return result;
}