我使用了一些代码来创建一些对象(比如DependencyProperty),它使用了一个Expression,所以我可以使用单个lamda检索属性名称和属性的返回类型
public static class DependencyPropertyOf<TOwner>
{
public static IDependencyPropertyBuilder<TOwner, TProp> From<TProp>(Expression<Func<TOwner, TProp>> propSelected)
{
if (propSelected.Body is MemberExpression propExp && propExp.Member is PropertyInfo propInfo)
{
return new DependencyPropertyBuilder<TOwner, TProp>(propInfo.Name);
}
throw new ArgumentException("Specify a property in the expression");
}
}
// Usage
public static readonly DependencyProperty SomethingProperty
= DependencyPropertyOf<MyClass>.From(myClass => myClass.Something);
我想做同样的事情,但是使用指向C#事件的lambda,使用代码将是
public static readonly RoutedEvent HoveredEvent =
RoutedEventOf<MyClass>.RegisterRoutedEvent(x => x.Hovered);
public event RoutedEventHandler Hovered
{
add => this.AddHandler(HoveredEvent, value);
remove => this.RemoveHandler(HoveredEvent, value);
}
public static class RoutedEventOf<TOwner>
{
public static IRoutedEventBuilder<TOwner, TProp> From<TProp>(Expression<Func<TOwner, TProp>> propSelected)
{
if (propSelected.Body is MemberExpression propExp && propExp.Member is PropertyInfo propInfo)
{
return new RoutedEventBuilder<TOwner, TProp>(propInfo.Name);
}
throw new ArgumentException("Specify an event in the expression");
}
public static RoutedEvent RegisterRoutedEvent<TProp>(Expression<Func<TOwner, TProp>> propSelected, Action<IRoutedEventBuilder<TOwner, TProp>> callback = null)
{
var builder = RoutedEventOf<TOwner>.From(propSelected);
callback?.Invoke(builder);
return builder.RegisterRoutedEvent();
}
}
但编译器抱怨The event 'MyClass.Hovered' can only appear on the left hand side of += or -=
似乎非常敏感,因为编译器为我认为的事件做了很多额外的隐形工作。
所以我的问题是:有没有办法使用Expression&lt;&gt;在C#中指定事件?
相关:Is it possible to target an EventHandler in a lambda expression?
编辑:添加了RoutedEventOf代码,到目前为止它与DependencyPropertyOf&lt;&gt;基本相同因为我找不到与https://referencesource.microsoft.com/#System.Core/Microsoft/Scripting/Ast/LambdaExpression.cs,51d6d604b8c53dc8
中的事件相关的内容