从表达式对象e中提取Func <t,u =“”>(其中用法保证typeof(e)== typeof(Expression <func <t,u>&gt;))</func <t,u> </t ,>

时间:2015-04-06 11:11:43

标签: c# generics lambda expression

我有一个希望存储在集合中的泛型类。因此,我采用了通常的方法来创建泛型继承的抽象类,并在顶部添加泛型属性(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,我不知道如何指定它,而不是 what 那些类型的args将是。

任何人都知道如何解决这个问题?

请注意,我实际上打算用这些Expression做的事情也可能会出现。实际的类有4个typeargs和3个表达式。所有这三个都用作指定属性名称的方法(用于属性更改通知目的),但第3个也需要能够编译,以便为我提供一种方法来获取表达式的当前值类型为T的对象。这意味着,在大多数情况下,我并不真正关心内部Func,只是Expression.Body最右边的叶子评估的字符串,但至少在一个案例中,我非常关心编译和评估Func

NB2:每次创建使用它的对象时,都希望这段代码会运行一堆表达式,但是不希望在创建对象后运行它 - 所以我原则上可以使用反射。

编辑:大大更新了代码,以便更清楚地了解它的用途。

1 个答案:

答案 0 :(得分:0)

使用Expression代替使用非通用LambdaExpression,因此您可以访问ParametersCompileExpression全部为LambdaExpression(参见定义:

public sealed class Expression<TDelegate> : LambdaExpression