表达式树LINQ得到一个参数的值? [英] expression trees linq get value of a parameter?
本文介绍了表达式树LINQ得到一个参数的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
AddOptional< tblObject>(X => x.Title,objectToSend.SupplementaryData);
私有静态无效AddOptional< Af - Ag型>(表达式来; Func键< Af - Ag型,串>> EXPR,字典<字符串,字符串>字典)
{
字符串propertyName的;
线为PropertyValue;
表达表达=(表达式)expr的;
,而(expression.NodeType == ExpressionType.Lambda)
{
表达式=((LambdaExpression)的表达)。体;
}
}
在上面的代码中,我想获得的实际值产权,不ONY PROPERT的名字,这可能吗?
解决方案
私有静态无效的主要(字串[] args)
{
CompileAndGetValue< tblObject>(X => x.Title,新tblObject(){标题=测试});
}
私有静态无效CompileAndGetValue< Af - Ag型>(
表达式来; Func键< Af - Ag型,串>> EXPR,
Af - Ag型OBJ)
{
//你仍然可以得到名在此
Func键< Af - Ag型,串> FUNC = expr.Compile();
串propretyValue = FUNC(OBJ);
Console.WriteLine(propretyValue);
}
不过,你必须意识到,这可能是非常慢的。你应该衡量它在你的情况如何执行
如果你不喜欢通过你的对象:
私有静态无效的主要(字串[] args)
{
变种yourObject =新tblObject {标题=测试};
CompileAndGetValue(()=> yourObject.Title);
}
私有静态无效CompileAndGetValue(
表达式来; Func键<串>>表达式)
{
//你仍然可以获得此名称
VAR FUNC = expr.Compile();
串propretyValue = FUNC();
Console.WriteLine(propretyValue);
}
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;
}
}
In Above code i would like to get actual value of property title, not ony propert name , is it possible ?
解决方案
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);
}
However, you must be aware that this can be quite slow. You should measure how it performs in your case.
If you don't like to pass your object:
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);
}
这篇关于表达式树LINQ得到一个参数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文