ASP.NET MVC是否允许私有ViewModel构造函数? [英] Does ASP.NET MVC allow private ViewModel constructor?

查看:56
本文介绍了ASP.NET MVC是否允许私有ViewModel构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是,正如标题所示,MVC模型绑定程序是否允许视图模型对象的私有构造函数.显然没有,即使有私有的无参数构造函数也说MissingMethodException: No parameterless constructor defined for this object.. 如果不允许使用私有构造函数,是否有建筑上的解决方法?

The question is, as in title, whether the MVC model binder allow private constructors for the view model objects. Apparently it doesn't, saying MissingMethodException: No parameterless constructor defined for this object. even if there is a private parameterless constructor. In case if there is no private constructor allowed, is there an arhitectural workaround?

这样的构造函数可能对确保只有模型绑定器才能创建其字段可能不会被一致填充的ViewModel对象很有用-在代码的其他部分中,有些字段被遗忘完成的可能性不大.

Such constructor might be useful to ensure that only the model binder could create ViewModel objects whose fields might not be consistently filled - there would be no chance that in other parts of code some fields are forgotten to complete.

在类似情况下,实体框架可以使用私有构造函数和私有属性.

Entity Framework, in a similar situation, can use private constructor and private properties.

推荐答案

不,不是.

如果要防止实际代码调用该构造函数,可以将[Obsolete("For model binding only", true)]添加到公共构造函数中.如果显式调用了构造函数,则将导致编译器错误.

If you want to prevent actual code from calling that constructor, you can add [Obsolete("For model binding only", true)] to a public constructor. This will cause a compiler error if the constructor is explicitly called.

这篇关于ASP.NET MVC是否允许私有ViewModel构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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