繁体   English   中英

提取功能 <T, U> 来自Expression对象e(使用保证typeof(e)== typeof(Expression <Func<T,U> &gt;))

[英]Extract a Func<T, U> from Expression object e (where usage guarantees typeof(e) == typeof(Expression<Func<T,U>>))

我有一个通用类,希望存储在集合中。 因此,我放弃了创建泛型继承的抽象类的常规方法,并在顶部添加了泛型属性(nb:这种方法的新特性,所以可能我还是在做错什么)。

最终结果是,我的通用类如下所示:

public class DependencyDeclaration<TDependantHost, TDependant, TFoundationHost, TFoundation> : DependencyDeclaration {

    public DependencyDeclaration(Expression<Func<TDependandHost, TDependant>> dependantRef, Expression<Func<TFoundationHost, TFoundation>> foundationRef, Expression<Func<TDependantHost, TFoundationHost>> foundationHostRef)

    public Expression<Func<TDependantHost, TDependant>> DependantRef {get;private set;}
    public Expression<Func<TDependantHost, TDependant>> FoundationRef {get;private set;}
    public Expression<Func<TDependantHost, TDependant>> FoundationHostRef {get; private set;}

}

和基类:

public abstract class DependencyDeclaration {
    public string GetDependantName() {
        // Some code to return the name of the leaf property from 
        // DependantRef, roughly akin to GetPropertyNameFromExpression
        // in BindableObjectBase from
        // http://www.pochet.net/blog/2010/07/02/inotifypropertychanged-automatic-dependent-property-and-nested-object-support/

        var e = this
            .GetType()
            .GetProperties()
            .Where(p=>p.Name=="DependantRef")
            .First()
            .GetValue(this) as Expression;
        return GetPropertyName(e).Name; // GetPropertyName requires a Func<T,U>, so this doesn't work as is.
    }

    public string GetFoundationName(Expression e) {
        // ... similar implementation to GetDependantName
    }


    public string GetFoundationHostName(Expression e) {
        // ... similar implementation to GetDependantName
    }

    public object GetFoundationHostRef(object dependantHost, Expression e) {
        // Evaluates this.FoundationHostRef via reflection against 
        // dependantHost.
        // Will function based on the comment below about using 
        // LambdaExpression, so not that worried about this one.
        // Something like, though:
        var e = this
            .GetType()
            .GetProperties()
            .Where(p=>p.Name=="DependantRef")
            .First()
            .GetValue(this) as LambdaExpression;
        if (e == null)
            return;

        var foundationHostRefFunc = e.Compile()
        return foundationHostRefFunc(dependantHost);
    }

    // Returns the PropertyInfo of a property via an Expression
    // as provided [here][http://stackoverflow.com/a/672212/847721]
    public GetPropertyInfo(Expression<Func<T, U>> targetExpression) 
    {
        // ... Magic expression parsing stuff ...
    }
}

通过使用例如,将在支持ISupportsDependencyManager的类的静态构造上填充此类声明的列表。

public class MyClassWithCalculatedProperties : ISupportsDependencyManager {
    // MyPropertySource inherits from INotifyPropertyChanged
    public object MyPropertySource {get;set;}

    // Trite example calculated property. Obviously actual calculated 
    // properties could be arbitrary.
    public int MyCalculatedProperty 
    {
        get {
            return MyPropertySource.SomeProperty + 50;
        }
    }
    private static DependencyDeclaration MyCalculatedPropertyDependencies = 
        new DependencyDelcaration<MyClassWithCalculatedProperties, int, MyPropertySource, int>(
            (dependantHost)=>dependantHost.MyCalculatedProperty,
            (foundationHost)=>foundationHost.SomeProperty,
            (dependantHost)=>dependantHost.MyPropertySource
        );

    static MyClassWithCalculatedProperties() 
    {
        // Static constructor iterates over the properties in the type
        // using DependencyManager and appends them to a list that 
        // DependencyManager maintains of DependencyDeclaration instances
        // 
        // This is where I'm going to generate a list of DependencyDeclarations - see below.
        DependencyManager
            .RegisterDependencies(
                typeof(MyClassWithCalculatedProperties)
            );
    }

    public MyClassWithCalculatedProperties() 
    {
        // Constructor for MyClassWithCalculatedProperties

        // Attach event handlers that allow calculated properties to 
        // have notifications on them.
        DependencyManager.AttachPropertyChangedHandlers(this)
    }
}

// This isn't finished yet, so expect bugs in ANY event 
// (not certain I'm using reflection right)
public class DependencyManager 
{
    private static ConcurrentDictionary<Type, ConcurrentBag<DependencyDeclaration>> _ParsedDependencies;

    // This is where I need the abstract class and/or interface. It 
    // allows all DependencyDeclarations to co-exist in the same 
    // collection to avoid needing to parse the type using reflection
    // more than once in a given program execution.
    public static RegisterDependencies(Type targetType) 
    {
        var dependencyDeclarations = 
            targetType
                .GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)
                .Where(fi => fi.FieldType == typeof(DependencyDeclaration))
                .Select(fi => fi.GetValue(targetType));
        ConcurrentBag<DependencyDeclaration> container = GetManagedDependencyContainer(targetType);
        dependencyDeclarations
            .Cast<DependencyDeclaration>()
            .ToList()
            .ForEach(d => container.Add(d));
    }

    /*
    * Other methods of DependencyManager
    */

}

这给我带来了两个问题:

  • 在需要调用GetUonTExpression<T,U> ,我不知道TU是什么(我确定它们已埋在要传递的arg中,但不确定如何在其中提取或调用任何事件)。 可能是通过反射,但不确定要使用的特定反射位。
  • 如果我真的想对表达式求值,那么我找不到办法-缺少编译方法,可能是因为不知道它是Func表达式。 然而,尽管我知道这将是一个Func<>我知道Func<>将有两个类型指定参数时,我不知道如何指定,而不是那些什么类型ARGS会。

任何人都有一个想法如何去做?

注意,我实际上打算如何处理这些Expression 实际的类有4个typeargs和3个表达式。 所有这三个都用作指定属性名称的方式(出于通知属性更改的目的),但是第三个属性也需要能够进行编译,以便为我提供一种在针对表达式求值时获取表达式当前值的方法这是类型T的对象。这意味着,在大多数情况下,我并不真正在乎内部Func ,而只是在Expression.Body最右边的叶子求值的字符串,但是至少在某些情况下,我确实在乎编译和评估Func

NB2:每次创建使用该代码的对象时,该代码都应在一系列表达式中运行,但不应在创建对象后运行该代码-原则上我可以接受反射。

编辑:实质性地更新了代码,以使您对此有一个更清晰的认识。

可以使用LambdaExpression而不是使用非泛型Expression ,这样您就可以访问ParametersCompile 表达式都是LambdaExpression (请参阅定义:

public sealed class Expression<TDelegate> : LambdaExpression

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM