我有以下情况:
public JsonResult ChangeFilterList(int option)
{
var data = new[] { new { Text = "Unknown option", Value = -1 } };
switch (option)
{
case 2: data = _departmentnameRepository.All.Select(x => new { Text = x.DeptName, Value = x.Id }).ToArray();
break;
case 3: data = Session["projectid"] == null
? _assetSequenceRepository.All.Select(x => new { Text = x.AssetShotName, Value = x.Id }).ToArray()
: _assetSequenceRepository.FindBy(p => p.ProjectId == (int)Session["projectid"]).Select(x => new { Text = x.AssetShotName, Value = x.Id }).ToArray();
break;
default: data = _userRepository.All.Select(x => new { Text = x.DisplayName, Value = x.UserID }).ToArray();
break;
}
return Json(data, JsonRequestBehavior.AllowGet);
}
case2
看起来不错,default
但抱怨案例 3(有条件)说:Cannot implicitly convert type 'AnonymousType#1[]' to 'AnonymousType#2[]'
。不?:
应该能够决定类型,因为我已经提供了匿名 as 的蓝图var data = new[] { new { Text = "Unknown option", Value = -1 } };
。
解决方案:
@Darin Dimitrov 的回答很好,但我想对匿名类型进行一些测试(简单的情况总是需要它)。正如@Douglas 所怀疑的那样:我assetSequenceRepository
提供id
aslong
而匿名Value
则支持int
not long
。由于 C# 编译器没有隐式long
转换为int
,我得到了错误。编译片段是:
public JsonResult ChangeFilterList(int option = 3)
{
var data = new[] { new { Text = "Unknown option", Value = long.MaxValue } };
switch (option)
{
case 2: data = _departmentnameRepository.All.Select(x => new { Text = x.DeptName, Value = (long)x.Id }).ToArray();
break;
case 3: data = Session["projectid"] == null
? _assetSequenceRepository.All.Select(x => new { Text = x.AssetShotName, Value = x.Id }).ToArray()
: _assetSequenceRepository.FindBy(p => p.ProjectId == (int)Session["projectid"]).Select(x => new { Text = x.AssetShotName, Value = x.Id }).ToArray();
break;
default: data = _userRepository.All.Select(x => new { Text = x.DisplayName, Value = (long)x.UserID }).ToArray();
break;
}
return Json(data, JsonRequestBehavior.AllowGet);
}