2017-04-06 19 views
0

我必须使用反射来循环反射对象的某些属性,并收集它们的PropertyInfo对象。c#PropertyInfo提取内部表达式

其中一些属性的类型为Expression<Func<Type1,string>>,我必须从属性信息中提取基础表达式。我试过myPropertyInfo.GetValue(parParameter) as LambdaExpression,但它似乎没有工作。

任何人都可以给我一些指针吗?

+0

可能你可以把'dynamic'用在这里很好用吗? – Fabjan

+3

请显示您目前为止的代码,以便更容易地查看问题的发生位置。你知道编译时'Type1'和'string'的类型吗?我不确定,但我认为从表达式>不是'LambdaExpresssion'_。你想用这个价值做什么? –

回答

3

您对myPropertyInfo.GetValue(parParameter) as LambdaExpression的使用是可疑的,因为参数和表达式是两个不同的东西。看起来你在做反思之后混合了你的变量。下面是一个可能有助于澄清事情的例子:

class Type1 { public string Name { get; set; } } 
class Data { public Expression<Func<Type1, string>> Ex { get; set; } } 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var d = new Data { Ex = t => t.Name }; 
     var pi = d.GetType().GetProperties().Single(); 
     var ex = pi.GetValue(d) as LambdaExpression; 
     Console.WriteLine(pi.GetValue(d).GetType()); 
     Console.WriteLine(ex); 
     Console.WriteLine(ex.Parameters.Single()); 
    } 
}