Browse Source

Don't convert to compatible types

#15
Sebastien Ros 11 years ago
parent
commit
cff2df81eb
2 changed files with 44 additions and 2 deletions
  1. 38 2
      Jint.Tests/Runtime/InteropTests.cs
  2. 6 0
      Jint/Runtime/Interop/DefaultTypeConverter.cs

+ 38 - 2
Jint.Tests/Runtime/InteropTests.cs

@@ -1,6 +1,5 @@
 using System;
 using System.Collections.Generic;
-using System.Runtime.Remoting.Messaging;
 using Jint.Native;
 using Jint.Native.Object;
 using Xunit;
@@ -384,8 +383,35 @@ namespace Jint.Tests.Runtime
 
         }
 
+        [Fact]
+        public void ShouldNotTryToConvertCompatibleTypes()
+        {
+            _engine.SetValue("a", new A());
+
+            RunTest(@"
+                assert(a.Call3('foo') === 'foo');
+                assert(a.Call3(1) === '1');
+            ");
+        }
 
-        public class Person
+        [Fact]
+        public void ShouldNotTryToConvertDerivedTypes()
+        {
+            _engine.SetValue("a", new A());
+            _engine.SetValue("p", new Person { Name = "Mickey"});
+
+            RunTest(@"
+                assert(a.Call4(p) === 'Mickey');
+            ");
+        }
+
+
+        public interface IPerson
+        {
+            string Name { get; }
+        }
+
+        public class Person : IPerson
         {
             public string Name { get; set; }
             public int Age { get; set; }
@@ -413,6 +439,16 @@ namespace Jint.Tests.Runtime
                 return x;
             }
 
+            public string Call3(object x)
+            {
+                return x.ToString();
+            }
+
+            public string Call4(IPerson x)
+            {
+                return x.ToString();
+            }
+
         }
     }
 }

+ 6 - 0
Jint/Runtime/Interop/DefaultTypeConverter.cs

@@ -6,6 +6,12 @@ namespace Jint.Runtime.Interop
     {
         public object Convert(object value, Type type, IFormatProvider formatProvider)
         {
+            // don't try to convert if value is derived from type
+            if (type.IsInstanceOfType(value))
+            {
+                return value;
+            }
+
             return System.Convert.ChangeType(value, type, formatProvider);
         }
     }