Skip to content

Commit

Permalink
fix discriminator on abstract classes
Browse files Browse the repository at this point in the history
fix [feature request] Allow fields and properties of Type ISomeInterface #11
  • Loading branch information
Michael Catanzariti committed Sep 2, 2019
1 parent 485fa19 commit 2fe6f9e
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
74 changes: 74 additions & 0 deletions src/Dahomey.Cbor.Tests/Issues/Issue0020.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using Dahomey.Cbor.Attributes;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;

namespace Dahomey.Cbor.Tests.Issues
{
public class Issue0020
{
public class Tree
{
[CborProperty("age")]
public readonly int _age;

[CborProperty("fruit")]
public Fruit _fruit;

[CborConstructor]
public Tree(int age, Fruit fruit)
{
_age = age;
_fruit = fruit;
}
}

public abstract class Fruit
{
public string id2 = "myid"; // if I remove this it won't throw
}

[CborDiscriminator("Apple")]
public class Apple : Fruit
{
[CborProperty("type")]
public const string type = "I am an apple";
}

[CborDiscriminator("Orange")]
public class Orange : Fruit
{
[CborProperty("type")]
public const string type = "I am an orange";
}

[Fact]
public void TestWrite()
{
CborOptions options = new CborOptions();
options.Registry.DefaultDiscriminatorConvention.RegisterAssembly(typeof(Fruit).Assembly);

Tree tree = new Tree(10, new Apple());

const string hexBuffer = "A2636167650A656672756974A3625F74654170706C6564747970656D4920616D20616E206170706C6563696432646D796964";
Helper.TestWrite(tree, hexBuffer, null, options);
}

[Fact]
public void TestRead()
{
CborOptions options = new CborOptions();
options.Registry.DefaultDiscriminatorConvention.RegisterAssembly(typeof(Fruit).Assembly);

const string hexBuffer = "A2636167650A656672756974A3625F74654170706C6564747970656D4920616D20616E206170706C6563696432646D796964";
Tree tree = Helper.Read<Tree>(hexBuffer, options);

Assert.NotNull(tree);
Assert.Equal(10, tree._age);
Assert.NotNull(tree._fruit);
Assert.IsType<Apple>(tree._fruit);
Assert.Equal("myid", ((Apple)tree._fruit).id2);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public override void Write(ref CborWriter writer, T value)
obj = value,
};

if (!_isInterfaceOrAbstract && value.GetType() != typeof(T))
if (_objectMapping.CreatorMapping == null && value.GetType() != typeof(T))
{
context.state = MapWriterContext.State.Discriminator;
context.objectConverter = (IObjectConverter)_registry.ConverterRegistry.Lookup(value.GetType());
Expand Down

0 comments on commit 2fe6f9e

Please sign in to comment.