Skip to content

Commit

Permalink
Try initialize interop object members with upper and lower first char (
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma authored Feb 26, 2024
1 parent 895b8d4 commit 107f543
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
22 changes: 22 additions & 0 deletions Jint.Tests/Runtime/InteropTests.MemberAccess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -234,5 +234,27 @@ public TValue this[string key]
public bool TryGetValue(string key, [MaybeNullWhen(false)] out TValue value) => _dictionary.TryGetValue(key, out value);
IEnumerator IEnumerable.GetEnumerator() => _dictionary.GetEnumerator();
}

public class ClassWithData
{
public DataType Data { get; set; }

public class DataType
{
public string Value { get; set; }
}
}

[Fact]
public void NewTypedObjectFromUntypedInitializerShouldBeMapped()
{
var engine = new Engine();

engine.SetValue("obj", new ClassWithData());
engine.Execute(@"obj.Data = { Value: '123' };");
var obj = engine.Evaluate("obj").ToObject() as ClassWithData;

Assert.Equal("123", obj?.Data.Value);
}
}
}
4 changes: 2 additions & 2 deletions Jint/Runtime/Interop/DefaultTypeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,8 @@ private bool TryConvert(
continue;
}

var name = member.Name.UpperToLowerCamelCase();
if (typeDescriptor.TryGetValue(value, name, out var val))
if (typeDescriptor.TryGetValue(value, member.Name, out var val)
|| typeDescriptor.TryGetValue(value, member.Name.UpperToLowerCamelCase(), out val))
{
var output = Convert(val, member.GetDefinedType(), formatProvider);
member.SetValue(obj, output);
Expand Down
4 changes: 2 additions & 2 deletions Jint/Runtime/Interop/TypeDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public bool TryGetValue(object target, string member, [NotNullWhen(true)] out ob
// we could throw when indexing with an invalid key
try
{
var parameters = new[] { member, _valueType!.IsValueType ? Activator.CreateInstance(_valueType) : null };
object?[] parameters = [member, _valueType!.IsValueType ? Activator.CreateInstance(_valueType) : null];
var result = (bool) _tryGetValueMethod!.Invoke(target, parameters)!;
o = parameters[1];
return result;
Expand All @@ -211,7 +211,7 @@ public bool Remove(object target, string key)
return false;
}

return (bool) _removeMethod.Invoke(target, new object[] { key })!;
return (bool) _removeMethod.Invoke(target, [key])!;
}

public ICollection<string> GetKeys(object target)
Expand Down

0 comments on commit 107f543

Please sign in to comment.