有没有办法组合这个 C# 代码
本文关键字:代码 组合 有没有 | 更新日期: 2023-09-27 18:32:53
我有以下代码。在我看来,有一种方法可以将其组合成一个语句,但我不确定如何做到这一点。
List<SelectListItem> items = new List<SelectListItem>();
var emptyItem = new SelectListItem(){
Value = "",
Text = "00"
};
items.Add(emptyItem);
ViewBag.AccountIdList = new SelectList(items);
有人可以告诉我是否可以简化这一点。
谢谢
是的,可以同时使用集合和对象初始值设定项来创建项,将其添加到列表中,并将列表全部包装在一个语句中。
ViewBag.AccountIdList = new SelectList(
new List<SelectListItem>
{
new SelectListItem
{
Value = "",
Text = "00"
}
});
上面的缩进样式是我更喜欢在自己的行上键入所有卷曲的方式,但如果需要,您甚至可以单行。
无论哪种方式,它都是一个单一的语句。
顺便说一下,由于您只是将List<SelectListItem>
传递给SelectList
构造函数,这需要IEnumerable
,因此您可以只传递一个数组 1 而不是列表以获得更高的性能:
ViewBag.AccountIdList = new SelectList(
new []
{
new SelectListItem
{
Value = "",
Text = "00"
}
});
在这种情况下,两者都会工作相同,后者效率更高,但两者都很好,这取决于您喜欢哪个。 有关更多信息,我做了一个简短的博客文章,比较了将单个项目作为IEnumerable<T>
序列返回的不同方法。
ViewBag.AccountIdList = new SelectList(new List<SelectListItem> { new SelectListItem { Value = "", Text = "00"} });
试试这个:
var items = new List<SelectListItem>()
{
new SelectListItem { Value = "", Text = "00" }
}
ViewBag.AccountIdList = new SelectList(items);
像这样的东西将是你能得到的最接近的。
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem(){
Value = "",
Text = "00"
});
ViewBag.AccountIdList = new SelectList(items);
ViewBag.AccountIdList = new SelectList(List items = new List { new SelectListItem{Value=",Text="00"}});
ViewBag.AccountIdList = new List<SelectListItem>{new SelectListItem{Value = "", Text = "00"}};
可读性较差的可测试性,IMO ...但你可以写:
items.Add(new SelectedListItem(){
Value = "",
Text = "00"
});
我不会在一个声明中推荐更多。此语句也可以重构为接受Value
和Text
参数的方法:
// now this is a unit testable method
SelectedListItem CreateSelectedItem (string value, string text) {
return new SelectedListItem(){
Value = value,
Text = text
};
}
现在你可以写下面的话,在简洁的同时,它的作用非常清楚:
ViewBag.AccountIdList = new SelectList(items.Add(CreateSelectedItem("someValue", "someText"));