Can I get specific metadata from a Func?

前端 未结 4 582
逝去的感伤
逝去的感伤 2021-02-04 17:16

Consider the following code:

string propertyName;
var dateList = new List() { DateTime.Now };
propertyName = dateList.GetPropertyName(dateTimeObj         


        
4条回答
  •  猫巷女王i
    2021-02-04 18:00

    here is a very easy and fast way to do it on this blog: http://blog.bittercoder.com/PermaLink,guid,206e64d1-29ae-4362-874b-83f5b103727f.aspx

    So given:

    Func func = Name => "Value";

    You can get the lambda parameter "Name" from the function delegate by calling:

    func.Method.GetParameters()[0].Name (would return "Name")

    Here's the revised Hash method from Andrey:

    public Dictionary Hash(params Func[] args)
    where T : class
    {
        var items = new Dictionary();
        foreach (var func in args)
        {
            var item = func(null);
            items.Add(func.Method.GetParameters()[0].Name, item);
        }
        return items;
    }
    

    Hope it helps, Patrick

提交回复
热议问题