我四处张望,因此无法找到问题的充分答案。
我有一个包装类,称为这样Title定义
public class Title
{
private readonly string _title;
public Title (string title) {
_title = title;
}
public static implicit operator Title(string title)
{
return new Title(title);
}
}
Run Code Online (Sandbox Code Playgroud)
我在ASP MVC项目中使用此类。现在,我定义了一个像这样的控制器:
public ActionResult Add(string title)
{
//stuff
}
Run Code Online (Sandbox Code Playgroud)
而且效果很好。但是,我希望将发布的字符串值自动绑定到Title构造函数,从而接受a Title 而不是a string作为参数:
public ActionResult Add(Title title)
{
//stuff
}
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用,因为我会收到错误消息:
参数字典包含parameter的空条目,这意味着模型绑定程序无法将字符串绑定到Title参数。
负责发布标题数据的HTML:
<form method="post" action="/Page/Add" id="add-page-form">
<div class="form-group">
<label for="page-title">Page title</label>
<input type="text" name="title" id="page-title">
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
我的问题分为两个部分:
1.为什么不可能做到这一点,我希望bodel绑定程序使用定义的隐式运算符来创建Title …
我正在尝试通过调用DTO列表中的select来创建DTO中的ViewModel列表.但是,编译器给出了一个错误说:
无法从指定类型参数的用法尝试推断方法的类型参数
我的问题是,为什么不能呢?双方TextSectionDTO并ImageSectionDTO都源于SectionDTO.我试图创建List的Sections,并且都TextSection与ImageSection衍生自Section.
我知道这个问题与此处发布的其他一些问题很接近,但我无法在那里找到答案.
这是我的代码:
private List<Section> BuildSectionViewModel(IEnumerable<SectionDTO> ss )
{
var viewModels = ss.Select((SectionDTO s) =>
{
switch (s.SectionType)
{
case Enums.SectionTypes.OnlyText:
return new TextSection((TextSectionDTO) s);
case Enums.SectionTypes.OnlyImage:
return new ImageSection((ImageSectionDTO) s);
default:
throw new Exception("This section does not exist - FIXME");
}
}).ToList();
return viewModels;
}
Run Code Online (Sandbox Code Playgroud)
当我更改类型以便我只接受超类SectionDTO并且只返回Section(我在这个场景中使它们都成为普通类)时,select会像你期望的那样工作.然后,当我将类型更改为TextSectionDTO和TextSection(更改摘要)时,select不再起作用.
我想要一个解决方案,这样我就可以使用我现在的构造工作,尽管我更感兴趣的是它为什么不能按原样运行.即使我可以让它工作,我也可能稍后重构.
注意:
所以对于这个小程序,我正在写我正在寻找解析Twitter的推文流.我使用Gson库,效果很好.Gson无法解析Twitters created_at datetime字段,因此我必须编写一个JsonDserializer需要通过GsonBuilder以下方式向解析器注册的自定义:
new GsonBuilder().registerTypeAdatapter(DateTime.class, <myCustomDeserializerType>)
Run Code Online (Sandbox Code Playgroud)
现在我的解串器运行良好,我能够解析Twitter的流.
但是,我试图用单元测试来覆盖我的程序,所以应该包含这个自定义反序列化器.
由于良好的单元测试是一个很好的隔离测试,我不想用一个Gson对象注册它,之后我将解析一个json字符串.我不希望是创造我的解串器的实例,只是传递表示日期时间的一般串,这样我就可以测试解串器没有它正在与别的集成.
JsonDeserializer的deserialize方法的签名如下:
deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
Run Code Online (Sandbox Code Playgroud)
假设我要解析以下数据:'Mon Mar 27 14:09:47 +0000 2017'.我如何转换输入数据以正确测试我的反序列化器.
我不是在寻找实际解析这个日期的代码,我已经覆盖了那个部分.我问我如何能够满足deserialize方法的签名,以便我可以模拟它在Gson其中的使用.