【问题标题】:Difference between these 2 function calls这两个函数调用之间的区别
【发布时间】: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");

它们的调用方式有什么区别吗?它们似乎都以完全相同的方式运行,它们之间是否存在效率差异? 解释将不胜感激:-)

【问题讨论】:

    标签: c# asp.net delegates


    【解决方案1】:

    参数调用一个函数。

    这会传递函数。

    TestClass.CreateList(obj.GetList, "Name", "Description");
    

    这会传递一个调用该函数的匿名函数。

    TestClass.CreateList(() => obj.GetList(), "Name", "Description");
    

    第二个的附加语法是不必要的。 Resharper 将提议用第一个替换第二个。

    【讨论】:

      【解决方案2】:

      在第一种情况下,您传递Lambda expression,而在第二种情况下,function 传递给delegate。不,效率没有区别。

      => 标记称为 lambda 运算符。它用于 lambda 表达式将左侧的输入变量与 右侧的 lambda 主体。 Lambda 表达式是内联的 类似于匿名方法但更灵活的表达式;他们是 广泛用于以方法语法表示的 LINQ 查询 来源MSDN

      委托是一种引用类型,可用于封装命名的 或匿名方法。委托类似于函数指针 C++;但是,委托是类型安全且安全的。对于应用 代表,请参阅代表和通用代表。 来源MSDN

      您可以在此处delegates-actions-funcs-lambdaskeeping-it-super-simple 阅读有关这些差异的信息

      【讨论】:

        猜你喜欢
        • 2011-12-28
        • 2018-11-01
        • 1970-01-01
        • 2017-12-04
        • 2015-12-26
        • 1970-01-01
        • 2023-01-28
        • 1970-01-01
        • 2023-01-10
        相关资源
        最近更新 更多