How do I create a delegate for a .NET property?

后端 未结 6 1835
眼角桃花
眼角桃花 2020-12-02 23:21

I am trying to create a delegate (as a test) for:

Public Overridable ReadOnly Property PropertyName() As String

My intuitive attempt was de

6条回答
  •  余生分开走
    2020-12-03 00:07

    This is good idea

    Test t = () => e.PropertyName; // C# 3.0
    

    But take care if your are doing something like this:

    List> funcs = new List>();
    foreach (var e in Collection)
       funcs.Add(new Func(() => e.Property));
    

    Calling this:

    foreach(var f in funcs)
       f();
    

    Will always return value of property of the last object in Collection

    In this case you should call method:

    foreach (var e in Collection)
       funcs.Add(new Func(e.GetPropValue));
    

提交回复
热议问题