Skip to content

Commit

Permalink
Merge pull request #1267 from Alxandr/fix/1218
Browse files Browse the repository at this point in the history
Fix handling of readonly private fields
  • Loading branch information
AArnott committed Jun 21, 2021
2 parents 09ab37c + db29bea commit 615a0b5
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
Expand Up @@ -1773,7 +1773,7 @@ public static ObjectSerializationInfo CreateOrNull(Type type, bool forceStringKe
{
FieldInfo = field,
IsReadable = allowPrivate || field.IsPublic,
IsWritable = allowPrivate || (field.IsPublic && !field.IsInitOnly),
IsWritable = (allowPrivate || field.IsPublic) && !field.IsInitOnly,
StringKey = firstMemberByName ? item.Name : $"{item.DeclaringType.FullName}.{item.Name}",
};
}
Expand Down Expand Up @@ -1956,7 +1956,7 @@ public static ObjectSerializationInfo CreateOrNull(Type type, bool forceStringKe
{
FieldInfo = item,
IsReadable = allowPrivate || item.IsPublic,
IsWritable = allowPrivate || (item.IsPublic && !item.IsInitOnly),
IsWritable = (allowPrivate || item.IsPublic) && !item.IsInitOnly,
};
if (!member.IsReadable && !member.IsWritable)
{
Expand Down
Expand Up @@ -157,6 +157,28 @@ internal class InternalClass
internal InternalEnum EnumProperty { get; set; }
}

[MessagePackObject]
public class PrivateReadonlyField
{
public static PrivateReadonlyField WithNullValue { get; } = new PrivateReadonlyField();

[Key(0)]
private readonly string field;

[SerializationConstructor]
public PrivateReadonlyField(string field)
{
this.field = field ?? "not null";
}

private PrivateReadonlyField()
{
}

[IgnoreMember]
public string Field => field;
}

#if !ENABLE_IL2CPP

[MessagePackObject]
Expand Down Expand Up @@ -329,6 +351,15 @@ public void InternalClassWithInternalEnum()
Assert.Equal(expected.EnumProperty, actual.EnumProperty);
}

[Fact]
public void PrivateReadonlyFieldSetInConstructor()
{
PrivateReadonlyField initial = PrivateReadonlyField.WithNullValue;
var bin = MessagePackSerializer.Serialize(initial, StandardResolverAllowPrivate.Options);
var deserialized = MessagePackSerializer.Deserialize<PrivateReadonlyField>(bin, StandardResolverAllowPrivate.Options);
Assert.Equal("not null", deserialized.Field);
}

#if !ENABLE_IL2CPP

[Fact]
Expand Down

0 comments on commit 615a0b5

Please sign in to comment.