【问题标题】:The type or namespace name 'K' does not exist in the current context当前上下文中不存在类型或命名空间名称“K”
【发布时间】: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();
        }

当我注释掉最后一行时,我可以构建它。当我调试带有最后一行注释的代码时,当我“观察”变量时也会遇到同样的问题。我读过这可能是因为我在发布模式下构建并且它丢弃了它认为不必要的任何变量,但是我在调​​试模式下构建所以......??

我觉得这些年来我已经多次遇到这个问题,并且总是“破解”我的方式来解决它。我想了解发生了什么,以便我可以解决问题,而不是想出一些巧妙的解决方法。

谢谢

【问题讨论】:

  • currentValuetype 是什么?这是编译器在编译期间必须确定的。但是您正试图涉及一个只能在运行时解析的表达式。那是行不通的。对运行时类型信息的引用不能用在需要使用类型本身的地方。
  • 直到运行时才知道。它可以是字符串,也可以是自定义类/对象定义。也许我正在尝试的事情无法完成,但为什么 propType 被报告为甚至不存在?即使我不能这样做,这能解释为什么 propType 声明失败了吗?

标签: c# visual-studio variables declare


【解决方案1】:
Expression.Lambda<Func<K>>(…)

那是创建一个 Expression&lt;Func&lt;K&gt;&gt; 需要 K 成为一个类型。

但是你有一个变量K

但是您似乎正在创建基于反射的表达式来获取值的属性值。只需坚持反射即可:

// theObject is the input
foreach (var pi in theObject.GetType().GetProperties()) {
  object val = pi.GetValue(theObject);
  // do something with val
}

【讨论】:

    【解决方案2】:

    这很可能与 foreach 上下文有关。考虑到它是一个动态上下文,这意味着“K”在每次迭代中都是一个全新的实例,Expression.Lambda 语句可能拒绝使用 K(也许它需要一个像类一样的常量,不确定)。尝试使用 for 和编号的索引,然后告诉我们结果。

    【讨论】:

    • 感谢您的建议,但是在更改为 FOR 循环后,我仍然观察到同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多