给定以下代码:
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?)
}
}
有没有办法正确解决这个问题?