Browse Source

Fix #2808: Insert cast to object when statically casting from dynamic to a reference type.

pull/2810/head
Siegfried Pammer 3 years ago
parent
commit
42668e810a
  1. 24
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/DynamicTests.cs
  2. 11
      ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs

24
ICSharpCode.Decompiler.Tests/TestCases/Pretty/DynamicTests.cs

@ -42,6 +42,10 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty @@ -42,6 +42,10 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
}
}
public interface I
{
}
private static dynamic field;
private static object objectField;
public dynamic Property { get; set; }
@ -492,6 +496,26 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty @@ -492,6 +496,26 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
return (int)(dynamic)o;
}
private static dynamic GetI()
{
return null;
}
public I Test()
{
return GetI();
}
public I Test1()
{
return (I)GetI();
}
public I Test2()
{
return (I)(object)GetI();
}
#if CS72
public void RefParams(ref object a, ref dynamic b, ref dynamic c)
{

11
ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs

@ -535,6 +535,17 @@ namespace ICSharpCode.Decompiler.CSharp @@ -535,6 +535,17 @@ namespace ICSharpCode.Decompiler.CSharp
.ConvertTo(targetType, expressionBuilder, checkForOverflow, allowImplicitConversion);
}
}
else if (type.Kind == TypeKind.Dynamic && targetType.IsReferenceType == true && !targetType.IsKnownType(KnownTypeCode.Object))
{
// "static" conversion between dynamic and a reference type requires us to add a cast to object,
// otherwise recompilation would produce a dynamic cast.
// (T)dynamicExpression is a "dynamic" cast
// (T)(object)dynamicExpression is a "static" cast
// as "dynamic" casts are handled differently by ExpressionBuilder.VisitDynamicConvertInstruction
// we can always insert the cast to object, if we encounter a conversion from any reference type to dynamic.
return this.ConvertTo(compilation.FindType(KnownTypeCode.Object), expressionBuilder)
.ConvertTo(targetType, expressionBuilder, checkForOverflow, allowImplicitConversion);
}
if (targetType.Kind.IsAnyPointer() && (0.Equals(ResolveResult.ConstantValue) || 0u.Equals(ResolveResult.ConstantValue)))
{
if (allowImplicitConversion)

Loading…
Cancel
Save