我得到以下代码的异常:
public class InnerClass
{
public object Value { get; set; }
}
public class OuterClass
{
// If I change the type of this property to "InnerClass" the exception is removed
public object Inner { get; set; }
}
private static void SmallSandbox()
{
var outer = new OuterClass()
{
Inner = new InnerClass()
{
Value = 2
}
};
var p = Expression.Parameter(typeof(OuterClass), "p");
Func<OuterClass, object> e = Expression.Lambda<Func<OuterClass, object>>(
Expression.Property(Expression.Property(p, "Inner"), "Value"),
p
).Compile();
var a = new[] { outer }.Select(e).First();
Console.WriteLine(a);
}
更改public object Inner { get; set; }
为public InnerClass Inner { get; set; }
删除异常。这不是一个选项,因为我让我的程序的使用者最终提供属性名称"Value"
和关联的对象 - 它无法提前知道。
我能做些什么来修复我的异常?