【发布时间】:2017-10-23 14:42:43
【问题描述】:
我知道这个问题已被问过一百万次,但似乎都提到了缺少对象或库引用。我用“TYPE”类型声明变量“K”。由于某种原因,这不会建立。
foreach (var propertyInfo in typeof(T).GetProperties())
{
//
// Gets the property from the obj
MemberExpression propertyExpression = Expression.Property(Expression.Constant(obj), propertyInfo);
//
// get the data type of the property
Type K = propertyExpression.Member.ReflectedType.UnderlyingSystemType;
//
// get the value of the property -- this line throws the error
var currentValue = Expression.Lambda<Func<K>>(propertyExpression).Compile().Invoke();
}
如果我注释掉它编译的例程的最后一行。
foreach (var propertyInfo in typeof(T).GetProperties())
{
//
// Gets the property from the obj
MemberExpression propertyExpression = Expression.Property(Expression.Constant(obj), propertyInfo);
//
// get the data type of the property
Type K = propertyExpression.Member.ReflectedType.UnderlyingSystemType;
//
// get the value of the property
//var currentValue = Expression.Lambda<Func<K>>(propertyExpression).Compile().Invoke();
}
当我注释掉最后一行时,我可以构建它。当我调试带有最后一行注释的代码时,当我“观察”变量时也会遇到同样的问题。我读过这可能是因为我在发布模式下构建并且它丢弃了它认为不必要的任何变量,但是我在调试模式下构建所以......??
我觉得这些年来我已经多次遇到这个问题,并且总是“破解”我的方式来解决它。我想了解发生了什么,以便我可以解决问题,而不是想出一些巧妙的解决方法。
谢谢
【问题讨论】:
-
currentValue的 type 是什么?这是编译器在编译期间必须确定的。但是您正试图涉及一个只能在运行时解析的表达式。那是行不通的。对运行时类型信息的引用不能用在需要使用类型本身的地方。 -
直到运行时才知道。它可以是字符串,也可以是自定义类/对象定义。也许我正在尝试的事情无法完成,但为什么 propType 被报告为甚至不存在?即使我不能这样做,这能解释为什么 propType 声明失败了吗?
标签: c# visual-studio variables declare