Skip to content

Commit

Permalink
#31 Add support for shimming conversion operators
Browse files Browse the repository at this point in the history
Please note, though, that the shim cannot be applied to a specific instance as the operator is static.
  • Loading branch information
sguldmund committed Jan 28, 2024
1 parent 91ac854 commit f8d961f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/Pose/Helpers/ShimHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ public static MethodBase GetMethodFromExpression(Expression expression, bool set
var newExpression = expression as NewExpression ?? throw new Exception($"Cannot cast expression to {nameof(NewExpression)}");
instanceOrType = null;
return newExpression.Constructor;
case ExpressionType.Convert:
var unaryExpression = expression as UnaryExpression ?? throw new Exception($"Cannot cast expression to {nameof(UnaryExpression)}");
instanceOrType = null;
return unaryExpression.Method;
default:
throw new NotImplementedException("Unsupported expression");
}
Expand Down
18 changes: 15 additions & 3 deletions src/Sandbox/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ namespace Pose.Sandbox
{
public class Program
{
public class OverridenOperatorClass
{
public static explicit operator bool(OverridenOperatorClass c) => false;
}

public static void Main(string[] args)
{
#if NET48
Expand All @@ -18,12 +23,19 @@ public static void Main(string[] args)
}, dateTimeShim);
#elif NETCOREAPP2_0
Console.WriteLine("2.0");
var dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 1, 1));

var sut1 = new OverridenOperatorClass();
var operatorShim = Shim.Replace(() => (bool) sut1)
.With(delegate (OverridenOperatorClass c) { return true; });

PoseContext.Isolate(
() =>
{
Console.WriteLine(DateTime.Now);
}, dateTimeShim);
var sut = new OverridenOperatorClass();
Console.WriteLine($"Result: {(bool)sut}");
Console.WriteLine($"Result: {(bool)sut1}");
}, operatorShim
);
#elif NET6_0
Console.WriteLine("6.0");
var dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 1, 1));
Expand Down

0 comments on commit f8d961f

Please sign in to comment.