Skip to content

Commit

Permalink
Allow access to declared Members on DynamicObject (#858)
Browse files Browse the repository at this point in the history
  • Loading branch information
windischb committed Apr 7, 2021
1 parent 546f1e8 commit 90eca8b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
15 changes: 13 additions & 2 deletions Jint.Tests/Runtime/InteropTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2344,12 +2344,17 @@ public void CanAccessDynamicObject()
Assert.Equal("a", engine.Execute("test.a").GetCompletionValue().AsString());
Assert.Equal("b", engine.Execute("test.b").GetCompletionValue().AsString());

engine.Execute("test.a = 5; test.b = 10;");
engine.Execute("test.a = 5; test.b = 10; test.Name = 'Jint'");

Assert.Equal(5, engine.Execute("test.a").GetCompletionValue().AsNumber());
Assert.Equal(10, engine.Execute("test.b").GetCompletionValue().AsNumber());

Assert.Equal("Jint", engine.Execute("test.Name").GetCompletionValue().AsString());
Assert.True(engine.Execute("test.ContainsKey('a')").GetCompletionValue().AsBoolean());
Assert.True(engine.Execute("test.ContainsKey('b')").GetCompletionValue().AsBoolean());
Assert.False(engine.Execute("test.ContainsKey('c')").GetCompletionValue().AsBoolean());
}

private class DynamicClass : DynamicObject
{
private readonly Dictionary<string, object> _properties = new Dictionary<string, object>();
Expand All @@ -2369,6 +2374,12 @@ public override bool TrySetMember(SetMemberBinder binder, object value)
_properties[binder.Name] = value;
return true;
}

public string Name { get; set; }
public bool ContainsKey(string key)
{
return _properties.ContainsKey(key);
}
}

[Fact]
Expand Down
10 changes: 5 additions & 5 deletions Jint/Runtime/Interop/ObjectWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -266,11 +266,6 @@ private static ReflectionAccessor GetAccessor(Engine engine, Type type, string m

private static ReflectionAccessor ResolvePropertyDescriptorFactory(Engine engine, Type type, string memberName)
{
if (typeof(DynamicObject).IsAssignableFrom(type))
{
return new DynamicObjectAccessor(typeof(void), memberName);
}

var isNumber = uint.TryParse(memberName, out _);

// we can always check indexer if there's one, and then fall back to properties if indexer returns null
Expand All @@ -282,6 +277,11 @@ private static ReflectionAccessor ResolvePropertyDescriptorFactory(Engine engine
return temp;
}

if (typeof(DynamicObject).IsAssignableFrom(type))
{
return new DynamicObjectAccessor(type, memberName);
}

// if no methods are found check if target implemented indexing
if (indexerAccessor != null)
{
Expand Down

0 comments on commit 90eca8b

Please sign in to comment.