【发布时间】:2013-10-07 12:02:21
【问题描述】:
我有以下场景:
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[]'。 ?: 不应该能够决定类型,因为我已经提供了匿名的蓝图为 var data = new[] { new { Text = "Unknown option", Value = -1 } };。
解决方案:
@Darin Dimitrov 的回答很好,但我想对匿名类型进行一些测试(简单的情况总是需要它)。
正如@Douglas 怀疑的那样:我的assetSequenceRepository 提供id 作为long 和匿名Value 支持int 而不是long。由于 C# 编译器不会将 long 隐式转换为 int,因此我得到了错误。编译sn-p是:
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);
}
【问题讨论】:
-
一个简单的解决方法是将您的
?:语句替换为if…else块。 -
我试过了,效果一样,不知道怎么回事。
-
if…else会收到什么错误消息?您是否在if分配、else分配或两者中都遇到错误? -
@BishnuRawal 请注意,将数据初始化为
new[] { new { Text = "Unknown option", Value = -1 } }是不必要的,因为它将在switch块中被丢弃。 -
@Douglas:
if和else两次出现相同错误。
标签: c# linq entity-framework asp.net-mvc-4 anonymous-types