次のコードがあるとします。
public enum Pet
{
Cat,
Dog
}
public interface IOwner
{
Pet Pet
{
get;
set;
}
}
public class Owner : IOwner
{
public Pet Pet
{
get;
set;
}
}
次のテストは失敗します。
[TestFixture]
public class ImpromptuInterfaceExample
{
private Owner owner;
private ExpandoObject dynamicOwner;
[SetUp]
public void SetUp()
{
owner = new Owner { Pet = Pet.Dog };
string serializedOwner = JsonConvert.SerializeObject(owner);
dynamicOwner = JsonConvert.DeserializeObject<ExpandoObject>(serializedOwner);
}
[Test]
public void InvalidCastException()
{
var duckType = ImpromptuDictionary.Create<IOwner>(dynamicOwner);
Assert.That(duckType.Pet, Is.EqualTo(owner.Pet)); // System.InvalidCastException : Invalid cast from 'System.Int64' to 'JsonSerializationDemo.Pet'.
}
[Test]
public void RuntimeBinderException()
{
var duckType = dynamicOwner.ActLike<IOwner>();
Assert.That(duckType.Pet, Is.EqualTo(owner.Pet)); // Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : Cannot implicitly convert type 'long' to 'JsonSerializationDemo.Pet'. An explicit conversion exists (are you missing a cast?)
}
}
この問題を適切に解決する方法はありますか?