ASP.NET MVC模型中的不可变结构 [英] Immutable structs in ASP.NET MVC model

查看:49
本文介绍了ASP.NET MVC模型中的不可变结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在模型中使用了不可变的结构,即:

If I use an immutable struct in my model, i.e.:

public struct ImmutableStruct
{
    private readonly int firstProperty;

    public ImmutableStruct(int firstProperty) : this()
    {
        this.firstProperty = firstProperty
    }

    public int FirstProperty { get { return firstProperty; } }
}

模型片段:

public class SomeModel
{
    public ImmutableStruct structProperty { get; set; }
}

视图片段:

@model SomeModel

<div>
    @Html.EditorFor(x = x.structProperty.FirstProperty)
</div>

模型绑定程序似乎无法绑定任何数据,当重新发布回控制器时.这是否意味着(1)不应使用不可变的结构,(2)需要使用自定义模型联编程序,(3)还是我需要做其他事情?

The model binder does not seem to be able to bind any data when posting back to the controller. Does this mean (1) that immutable structs should not be used, (2) need to use a custom model binder, (3) or I need to do something else instead?

推荐答案

MVC需要一个默认的无参数构造函数.您的构造函数不符合条件,因为它需要一个参数.MVC通过属性进行绑定,而您的属性没有设置器.

MVC requires a default parameterless constructor as far as I am aware. Your constructor does not qualify because it requires a parameter. MVC does binding via properties, and your property has no setter.

我相信自定义模型绑定程序将解决您的问题,从而允许您调用构造函数.似乎麻烦多于其应有的价值,尤其是因为您可能随时都需要在类中添加属性时修改自定义模型绑定程序.但我将由您决定.

I believe a custom model binder will solve your problem, allowing you to call the constructor. Seems alot more trouble than it's worth though, especially since you'll probably have to modify your custom model binder anytime you add properties to your class. But I'll leave that up to you to decide.

此模型绑定器中示例了如何将模型绑定到参数化构造函数的详细信息:

The details of how to do model binding to a parameterized constructor are exemplified in this model binder:

https://stackoverflow.com/a/13535545/84206

通知返回新公司(customProfile); 类似于 new ImmutableStruct(someValue)

这篇关于ASP.NET MVC模型中的不可变结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆