瀏覽代碼

Can call PascalCase .NET methods from JS using camelCase.

csabakiss 10 年之前
父節點
當前提交
04328349ba
共有 2 個文件被更改,包括 46 次插入0 次删除
  1. 15 0
      Jint.Tests/Runtime/InteropTests.cs
  2. 31 0
      Jint/Runtime/Interop/ObjectWrapper.cs

+ 15 - 0
Jint.Tests/Runtime/InteropTests.cs

@@ -125,6 +125,21 @@ namespace Jint.Tests.Runtime
             ");
         }
 
+        [Fact]
+        public void CanInvokeObjectMethodsWithPascalCase()
+        {
+            var p = new Person
+            {
+                Name = "Mickey Mouse"
+            };
+
+            _engine.SetValue("p", p);
+
+            RunTest(@"
+                assert(p.toString() === 'Mickey Mouse');
+            ");
+        }
+
         [Fact]
         public void CanSetObjectProperties()
         {

+ 31 - 0
Jint/Runtime/Interop/ObjectWrapper.cs

@@ -91,6 +91,24 @@ namespace Jint.Runtime.Interop
                 return descriptor;
             }
 
+            var pascalCasedPropertyName = char.ToUpperInvariant(propertyName[0]).ToString();
+            if (propertyName.Length > 1)
+            {
+                pascalCasedPropertyName += propertyName.Substring(1);
+            }
+
+            // look for methods using pascal cased name.
+            var pascalCasedMethods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public)
+                .Where(m => m.Name == pascalCasedPropertyName)
+                .ToArray();
+
+            if (pascalCasedMethods.Any())
+            {
+                var descriptor = new PropertyDescriptor(new MethodInfoFunctionInstance(Engine, pascalCasedMethods), false, true, false);
+                Properties.Add(propertyName, descriptor);
+                return descriptor;
+            }
+
             // if no methods are found check if target implemented indexing
             if (type.GetProperties().Where(p => p.GetIndexParameters().Length != 0).FirstOrDefault() != null)
             {
@@ -125,6 +143,19 @@ namespace Jint.Runtime.Interop
                 return descriptor;
             }
 
+            // try to find explicit method implementations using the pascal cased property name
+            var explicitPascalCasedMethods = (from iface in interfaces
+                                              from imethod in iface.GetMethods()
+                                              where pascalCasedPropertyName.Equals(imethod.Name)
+                                              select imethod).ToArray();
+
+            if (explicitPascalCasedMethods.Length > 0)
+            {
+                var descriptor = new PropertyDescriptor(new MethodInfoFunctionInstance(Engine, explicitPascalCasedMethods), false, true, false);
+                Properties.Add(propertyName, descriptor);
+                return descriptor;
+            }
+
             // try to find explicit indexer implementations
             var explicitIndexers =
                 (from iface in interfaces