【发布时间】:2017-10-20 15:25:47
【问题描述】:
专门使用 Func 关键字与委托进行一些练习,并注意到我可以通过 2 种不同的方式进行相同的函数调用。
public class TestClass
{
public string Name { get; set; }
public string Description { get; set; }
/// <summary>
/// Creates a SelectListItem
/// </summary>
/// <param name="function">Function which retrieves the data to populate the list</param>
/// <param name="key">The column name which contains the index/uniqueidentifier which is used to identify the object</param>
/// <param name="displayText">Column name for the text that will appear on the dropdown list</param>
/// <returns> A List of SelectListItem</returns>
public static List<SelectListItem> CreateList<T>(Func<List<T>> function, string key, string displayText)
{
var list = new List<SelectListItem>();
var model = function();
foreach (var item in model)
{
var property = item.GetType().GetProperty(key);
var text = item.GetType().GetProperty(displayText);
if (property != null && text != null)
{
list.Add(new SelectListItem()
{
Text = text.GetValue(item, null).ToString(),
Value = property.GetValue(item, null).ToString()
});
}
}
return list;
}
public List<TestClass> GetList()
{
List<TestClass> test = new List<TestClass>();
var t = new TestClass
{
Name = "T",
Description = "P"
};
test.Add(t);
return test;
}
}
调用如下:
var obj = new TestClass();
TestClass.CreateList(() => obj.GetList(), "Name", "Description");
TestClass.CreateList(obj.GetList, "Name", "Description");
它们的调用方式有什么区别吗?它们似乎都以完全相同的方式运行,它们之间是否存在效率差异? 解释将不胜感激:-)
【问题讨论】: