简体   繁体   English

使用ImpromptuInterface时如何解决此枚举转换问题?

[英]How do I resolve this enum cast issue when using ImpromptuInterface?

Given the following code: 给出以下代码:

public enum Pet
{
    Cat,
    Dog
}

public interface IOwner
{
    Pet Pet
    {
        get;
        set;
    }
}

public class Owner : IOwner
{
    public Pet Pet
    {
        get;
        set;
    }
}

The following tests fail: 以下测试失败:

[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?)
    }
}

Is there a way to properly resolve this problem? 有没有办法正确解决此问题?

Your line: 您的电话:

 var duckType = ImpromptuDictionary.Create<IOwner>(dynamicOwner);

Should have worked but there was a bug with Enums specifically in ImpromptuInterface that is now fixed in version 6.0 . 应该可以用,但是在ImpromptuInterface中有一个专门针对Enums的错误,现已在6.0版中修复 ImpromptuDictionary tries several ways to coerce a type at runtime and was using the wrong one for Enums. ImpromptuDictionary尝试了几种在运行时强制类型的方法,并为Enums使用了错误的方法。 So it works now. 因此,现在可以使用。

I think, the problem stems from fact, that Json serialiser serialises enums as numbers. 我认为,问题源于事实,Json序列化器将枚举序列化为数字。 But when it deserialises it into expando object, then it cannot possibly know, that the property is actualy an enum. 但是,当将其反序列化为expando对象时,就不可能知道该属性实际上是一个枚举。 This results in integer value in expando object. 这将在expando对象中产生整数值。

This then confuses the impromptu-interface and causes exception in casting proxy. 然后,这会混淆即兴接口,并在强制转换代理中导致异常。 I think this could be resolved here, that the proxy builder would check, if the target type is enum, and use working coversion of in into enum. 我认为这可以在此处解决,代理构建器将检查目标类型是否为枚举,并使用in的有效覆盖范围枚举。 But you should take it to official page . 但是你应该把它带到官方页面 I don't think SO can solve this problem. 我认为SO无法解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM