Retrieving Event name from lambda expression

2019-06-16 15:45发布

is there way how to get name ov event from Lambda expression like with property ( Retrieving Property name from lambda expression ) ?

Thanks

标签: c# lambda
2条回答
放我归山
2楼-- · 2019-06-16 16:02

Yes, it's just like getting the property name, but you must do it in the class that defines the event.

public class Foo
{
    public event EventHandler Bar;

    public string BarName
    {
        get
        {
            return this.GetEventName(() => this.Bar);
        }
    }

    private string GetEventName(Expression<Func<EventHandler>> expression)
    {
        return (expression.Body as MemberExpression).Member.Name;
    }
}

Enjoy.

查看更多
地球回转人心会变
3楼-- · 2019-06-16 16:13

No. C# lambdas don't support events, so there is no way of representing this. You'll have to use reflection.

查看更多
登录 后发表回答