提交 00cbe850 编写于 作者: N Neal Gafter 提交者: GitHub

Never offer to remove an unboxing cast, as it can cause an exception. (#13798)

Fixes #12572 
Fixes #10306
上级 647b08e2
......@@ -3856,5 +3856,36 @@ public async Task TupleWithDifferentNames()
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[WorkItem(12572, "https://github.com/dotnet/roslyn/issues/12572")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)]
public async Task DontRemoveCastThatUnboxes()
{
// The cast below can't be removed because it could throw a null ref exception.
await TestMissingAsync(
@"
using System;
class Program
{
static void Main()
{
object i = null;
switch ([|(int)i|])
{
case 0:
Console.WriteLine(0);
break;
case 1:
Console.WriteLine(1);
break;
case 2:
Console.WriteLine(2);
break;
}
}
}
");
}
}
}
......@@ -383,6 +383,11 @@ public static bool IsUnnecessaryCast(this CastExpressionSyntax cast, SemanticMod
// Explicit reference conversions can cause an exception or data loss, hence can never be removed.
return false;
}
else if (expressionToCastType.IsExplicit && expressionToCastType.IsUnboxing)
{
// Unboxing conversions can cause a null ref exception, hence can never be removed.
return false;
}
else if (expressionToCastType.IsExplicit && expressionToCastType.IsNumeric)
{
// Don't remove any explicit numeric casts.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册