代码之家  ›  专栏  ›  技术社区  ›  T W

表达式树linq获取参数的值?

  •  0
  • T W  · 技术社区  · 16 年前
    AddOptional<tblObject>(x =>x.Title, objectToSend.SupplementaryData);
    
    private static void AddOptional<TType>(Expression<Func<TType,string>> expr, Dictionary<string, string> dictionary)
    {
        string propertyName;
        string propertyValue;
    
        Expression expression = (Expression)expr;
        while (expression.NodeType == ExpressionType.Lambda)
        {
            expression = ((LambdaExpression)expression).Body;
        }
    }
    

    1 回复  |  直到 16 年前
        1
  •  3
  •   maciejkow    16 年前
    private static void Main(string[] args)
    {
        CompileAndGetValue<tblObject>(x => x.Title, new tblObject() { Title =  "test" });
    }
    
    private static void CompileAndGetValue<TType>(
        Expression<Func<TType, string>> expr,
        TType obj)
    {
        // you can still get name here
    
        Func<TType, string> func = expr.Compile();
        string propretyValue = func(obj);
        Console.WriteLine(propretyValue);
    }
    

    然而,你必须意识到这可能会很慢。你应该衡量它在你的案例中的表现。

        private static void Main(string[] args)
        {
            var yourObject = new tblObject {Title = "test"};
            CompileAndGetValue(() => yourObject.Title);
        }
    
    
        private static void CompileAndGetValue(
            Expression<Func<string>> expr)
        {
            // you can still get name here
    
            var func = expr.Compile();
            string propretyValue = func();
            Console.WriteLine(propretyValue);
        }