【发布时间】:2011-08-05 12:49:03
【问题描述】:
我有一个关于铸造类型的愚蠢但令人费解的问题。正如您从代码中看到的那样,我有一个变量 lprod_monthylReport,根据 ytm 的值可以是 List<Monthly_Report> 或只是 Monthly_Report。在这两种情况下,我都需要变量具有相同的名称。
var lprod_monthlyReport = new List<Monthly_Report>;
if (ytm == true)
{
lprod_monthlyReport = _ProductRep.GetSpecificArchiveReport(prod.Prod_ID, lmonth, lyear, item.item_ID);
}
else
lprod_monthlyReport = _ProductRep.GetSpecificYTMReport(prod.Prod_ID, item.item_ID);
问题是,如果我在每个 if(或 else)部分中声明变量,编译器会给出错误,因为它表示该变量已在此上下文中声明。
我已经尝试过投射
lprod_monthlyReport = (Monthly_Report) _ProductRep.GetSpecificArchiveReport(prod.Prod_ID, lmonth, lyear, item.Item_ID);
但它不起作用。我也尝试了 as 关键字但没有成功。
你能帮我解决这个问题吗?谢谢
弗朗西斯科
【问题讨论】:
-
GetSpecificArchiveReport 和 GetSpecificYTMReport 返回什么类型
-
为什么
lprod_monthlyReport必须成为List<Monthly_Report>,而不是你的方法返回什么? -
@Hath:感谢您的回答。 GetSpecificArchiveReport 返回一个 Monthly_Report 对象(它使用 Single 进行 LINQ 查询) GetSpecificYTMReport 返回一个 List(使用 Where 的 LINQ 查询)。
-
@Rowland Shaw:感谢您的回答。注意这两种方法是不同的,不仅仅是签名
标签: c# .net generics collections casting