这是我可以得到的最简洁的单线...
report.Load(Server.MapPath(string.Format("~/Content/StimulReports/{0}Group.mrt", data.CompareId == 2 ? "Month" : "Year")));
但是,看起来你只是想让事情看起来更干净。 数据调用和条件逻辑之间的抽象更多。 你可能想考虑让它们成为单独的方法,也许在你的报告对象上?
if(data.CompareId == 2)
report.LoadStimulReports(ReportGroup.Month);
else
report.LoadStimulReports(ReportGroup.Year);
使用枚举,扩展方法,你的报告对象的静态方法...
public enum ReportGroup
{
[DescriptionAttribute("~/Content/StimulReports/MonthGroup.mrt")]
Month,
[DescriptionAttribute("~/Content/StimulReports/YearGroup.mrt")]
Year
}
public static T GetAttribute<T>(this Enum e) where T : Attribute
{
System.Reflection.FieldInfo fi = e.GetType().GetField(e.ToString());
object[] o = (object[])fi.GetCustomAttributes(typeof(T), false);
return o.Length > 0 ? (T)o[0] : default(T);
}
public static void LoadStimulReports(ReportGroup reportGroup)
{
report.Load(Server.MapPath(reportGroup.GetAttribute<DescriptionAttribute>().Description));
}
现在你可以其他项目简单地添加到枚举,如果你需要的另一份报告。
[DescriptionAttribute("~/Content/StimulReports/WeekGroup.mrt")]
Week
它怎么不起作用?它没有编译?或者它没有产生预期的结果? – bump
在这种情况下,请勿使用三元运算符(?:)。你没有获得任何东西,只是让你的代码不易读。 – helb
我不明白为什么你提到“一行”,因为你将三元运算符分散在三行。如果您想要:只需删除换行符,就可以在一行中放入一个if! –