为什么从 int 到 intBox 的隐式转换在 Json.decode 或默认模型绑定中不起作用?

Why isn't an implicit conversion from int to intBox working in Json.decode or default modelbinding?

编辑:删除了问题的第一部分,因为它具有误导性且不完全相关。

由于各种原因,我已经到了可以真正使用将我的一些 Post body 参数装箱到他们模型中的能力的地步。

我开始这个只是接受默认的模型绑定器就可以工作™,它确实有效,但不适用于整数(?!)。示例:

public class IntBox
{
    public int Value;

    public IntBox(int value)
    {
        Value = value;
    }

    public static implicit operator IntBox(int value)
    {
        return new IntBox(value);
    }
}

public class StringBox
{
    public string Value;

    public StringBox(string value)
    {
        Value = value;
    }

    public static implicit operator StringBox(string value)
    {
        return new StringBox(value);
    }
}

public class BoolBox
{
    public bool Value;

    public BoolBox(bool value)
    {
        Value = value;
    }

    public static implicit operator BoolBox(bool value)
    {
        return new BoolBox(value);
    }
}

public class NeedQuery : StateFullQuery
{
    public StringBox[] TestStrings { get; set; } //"TestStrings":["a","b"]
    public IntBox[] TestInts { get; set; } //"TestInts":[1,2,3,4]
    public BoolBox[] TestBools { get; set; } //"TestBools":[true,false]
}

//Inside Controller:
public string Post([FromBody]NeedQuery query)
{
    //At this point query.TestStrings contains two StringBoxes with the expected values. As does query.TestBools
    // However, query.TestInts is empty.
}

我错过了什么?! Int 有什么特别之处以至于它们不能被 Modelbinder 隐式转换?我该如何解决这个问题?

非常感谢对此的帮助;如果没有大量重写,我会被阻止,直到我弄清楚。

注意:当我说我需要装箱 int 值时,这是为了 post 而简化问题,它比简单地装箱值要复杂一些。

发生这种情况的原因(简而言之)是在编译时推断隐式强制转换,而模型绑定器在运行时使用反射来设置值,此时存在两种不同的 - 不兼容 - 类型。

处理这种情况的最简单的解决方案通常是(例如)在你的模型上有一个 int[] 属性,绑定到它并让它简单地映射到一个 IntBox[] 属性 手动(例如通过自定义访问器)。

我不会 post "full" 解决方案,因为 - 如您所说 - 您的示例已简化;但是,希望这些信息足以让您理解和解决问题。

想通了。

这行不通:

public class IntBox
{
    public int Value;

    public IntBox(int value)
    {
        Value = value;
    }

    public static implicit operator IntBox(int value)
    {
        return new IntBox(value);
    }
}

这确实有效:

public class IntBox
{
    public int Value;

    public IntBox(int value)
    {
        Value = value;
    }

    public static implicit operator IntBox(Int64 value)
    {
        return new IntBox(value);
    }
}

很明显,64/32 位转换有些愚蠢。我可能不得不为 32 位和 64 位整数实现我的隐式转换,但至少我可以停止拉扯我的头发。也许这会在将来帮助其他人。