簡體   English   中英

從Linq表達式獲取參數值

[英]Get the parameter value from a Linq Expression

我有以下課程

public class MyClass
{
    public bool Delete(Product product)
    {
        // some code.
    }
}

現在我有一個看起來像這樣的助手類

public class Helper<T, TResult>
{

    public Type Type;
    public string Method;
    public Type[] ArgTypes;
    public object[] ArgValues;

    public Helper(Expression<Func<T, TResult>> expression)
    {
        var body = (System.Linq.Expressions.MethodCallExpression)expression.Body;

        this.Type = typeof(T);
        this.Method = body.Method.Name;
        this.ArgTypes = body.Arguments.Select(x => x.Type).ToArray();
        this.ArgValues = ???
    }
}

這個想法是從某個地方使用這個代碼:

// I am returning a helper somewhere
public Helper<T> GetMethod<T>()
{
    var product = GetProduct(1);
    return new Helper<MyClass>(x => x.Delete(product));
}

// some other class decides, when to execute the helper 
// Invoker already exists and is responsible for executing the method
// that is the main reason I don't just comile and execute my Expression
public bool ExecuteMethod<T>(Helper<T> helper)
{
    var instance = new MyClass();
    var Invoker = new Invoker(helper.Type, helper.Method, helper.ArgTypes, helper.ArgValues);
    return (bool)Invoker.Invoke(instance);
}

我被困的地方是如何從表達式本身中提取參數。

我找到了這種方式

((ConstantExpression)((MemberExpression)body.Arguments[0]).Expression).Value

這似乎是一個帶有“產品”字段的對象類型,但我相信必須有一個更簡單的解決方案。

有什么建議。

更新

為了澄清,我根據我想要的內容修改了我的代碼。 在我的真正的單詞應用程序中,我已經有一個類,但沒有表達式樹:

var helper = new Helper(typeof(MyClass), "Delete", 
    new Type[] { typeof(Product) }, new object[] {product}));

我的Helper<T>主要原因是如果方法簽名有效,則進行編譯時檢查。

更新2

這是我目前的實現,是否有更好的方法來訪問值,而不使用反射?

public Helper(Expression<Func<T, TResult>> expression)
{
    var body = (System.Linq.Expressions.MethodCallExpression)expression.Body;

    this.Type = typeof(T);
    this.Method = body.Method.Name;
    this.ArgTypes = body.Arguments.Select(x => x.Type).ToArray();

    var values = new List<object>();
    foreach(var arg in body.Arguments)
    {
        values.Add(
            (((ConstantExpression)exp.Expression).Value).GetType()
                .GetField(exp.Member.Name)
                .GetValue(((ConstantExpression)exp.Expression).Value);
        );
    }
    this.ArgValues = values.ToArray();
}

這種方法效果很好。 它返回Expression>的參數類型和值

    private static KeyValuePair<Type, object>[] ResolveArgs<T>(Expression<Func<T, object>> expression)
    {
        var body = (System.Linq.Expressions.MethodCallExpression)expression.Body;
        var values = new List<KeyValuePair<Type, object>>();

        foreach (var argument in body.Arguments)
        {
            var exp = ResolveMemberExpression(argument);
            var type = argument.Type;

            var value = GetValue(exp);

            values.Add(new KeyValuePair<Type, object>(type, value));
        }

        return values.ToArray();
    }

    public static MemberExpression ResolveMemberExpression(Expression expression)
    {

        if (expression is MemberExpression)
        {
            return (MemberExpression)expression;
        }
        else if (expression is UnaryExpression)
        {
            // if casting is involved, Expression is not x => x.FieldName but x => Convert(x.Fieldname)
            return (MemberExpression)((UnaryExpression)expression).Operand;
        }
        else
        {
            throw new NotSupportedException(expression.ToString());
        }
    }

    private static object GetValue(MemberExpression exp)
    {
        // expression is ConstantExpression or FieldExpression
        if (exp.Expression is ConstantExpression)
        {
            return (((ConstantExpression)exp.Expression).Value)
                    .GetType()
                    .GetField(exp.Member.Name)
                    .GetValue(((ConstantExpression)exp.Expression).Value);    
        }
        else if (exp.Expression is MemberExpression)
        {
            return GetValue((MemberExpression)exp.Expression);
        }
        else
        {
            throw new NotImplementedException();
        }
    }

您可以編譯參數表達式,然后調用它來計算值:

var values = new List<object>();
foreach(var arg in body.Arguments)
{
    var value = Expression.Lambda(argument).Compile().DynamicInvoke();
    values.Add(value);
}
this.ArgValues = values.ToArray();

以下是使用lambda創建委托的示例。 使用名為closure的C#功能將對象實例封裝到委托中。

MyClass instance = new MyClass();
    //This following line cannot be changed to var declaration 
    //since C# can't infer the type.
Func<Product, bool> deleteDelegate = p => instance.Delete(p);
Product product = new Product();
bool deleted = deleteDelegate(product);

或者,您正在嘗試創建一個自動化Currys的Helper。

public class Helper<T>
    where T : new()
{
    public TResult Execute<TResult>(Func<T, TResult> methodLambda)
    {
        var instance = new T();
        return methodLamda(instance);
    }
}

public void Main()
{
    var helper = new Helper<MyClass>();
    var product = new Product();
    helper.Execute(x => x.Delete(product));
}

但是我不得不說這個問題看起來很像創建一個Helper類來處理WCF代理的生命周期....你知道......只是說...在這種情況下這不是我怎么接近這個...只是因為這種方法將WCF特定代碼泄漏到您的域中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM