Skip to content

Commit f8d961f

Browse files
committed
#31 Add support for shimming conversion operators
Please note, though, that the shim cannot be applied to a specific instance as the operator is static.
1 parent 91ac854 commit f8d961f

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

src/Pose/Helpers/ShimHelper.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ public static MethodBase GetMethodFromExpression(Expression expression, bool set
3636
var newExpression = expression as NewExpression ?? throw new Exception($"Cannot cast expression to {nameof(NewExpression)}");
3737
instanceOrType = null;
3838
return newExpression.Constructor;
39+
case ExpressionType.Convert:
40+
var unaryExpression = expression as UnaryExpression ?? throw new Exception($"Cannot cast expression to {nameof(UnaryExpression)}");
41+
instanceOrType = null;
42+
return unaryExpression.Method;
3943
default:
4044
throw new NotImplementedException("Unsupported expression");
4145
}

src/Sandbox/Program.cs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ namespace Pose.Sandbox
66
{
77
public class Program
88
{
9+
public class OverridenOperatorClass
10+
{
11+
public static explicit operator bool(OverridenOperatorClass c) => false;
12+
}
13+
914
public static void Main(string[] args)
1015
{
1116
#if NET48
@@ -18,12 +23,19 @@ public static void Main(string[] args)
1823
}, dateTimeShim);
1924
#elif NETCOREAPP2_0
2025
Console.WriteLine("2.0");
21-
var dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 1, 1));
26+
27+
var sut1 = new OverridenOperatorClass();
28+
var operatorShim = Shim.Replace(() => (bool) sut1)
29+
.With(delegate (OverridenOperatorClass c) { return true; });
30+
2231
PoseContext.Isolate(
2332
() =>
2433
{
25-
Console.WriteLine(DateTime.Now);
26-
}, dateTimeShim);
34+
var sut = new OverridenOperatorClass();
35+
Console.WriteLine($"Result: {(bool)sut}");
36+
Console.WriteLine($"Result: {(bool)sut1}");
37+
}, operatorShim
38+
);
2739
#elif NET6_0
2840
Console.WriteLine("6.0");
2941
var dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 1, 1));

0 commit comments

Comments
 (0)