【问题标题】:variable 'x' of type 'Product' referenced from scope, but it is not defined从范围引用的“产品”类型的变量“x”,但未定义
【发布时间】:2011-06-08 01:56:17
【问题描述】:

我在类库项目中有一个名为Product 的类。我正在使用SubSonic SimpleRepository 来持久化对象。我在Product类中有一个方法如下:

public static IList<Product> Load(Expression<Func<Product, bool>> expression)
{
    var rep=RepoHelper.GetRepo("ConStr");
    var products = rep.Find(expression);
    return products.ToList();
}

我这样调用这个函数:

private void BindData()
{
    var list = Product.Load(x => x.Active);//Active is of type bool
    rptrItems.DataSource = list;
    rptrItems.DataBind();
}

BindData 调用Load 会引发异常:

variable 'x' of type 'Product' referenced from scope '', but it is not defined

我该如何解决这个问题。

编辑:- 通过单步执行SubSonic 代码,我发现此函数引发了错误

private static Expression Evaluate(Expression e)
{
    if(e.NodeType == ExpressionType.Constant)
        return e;
    Type type = e.Type;
    if(type.IsValueType)
        e = Expression.Convert(e, typeof(object));
    Expression<Func<object>> lambda = Expression.Lambda<Func<object>>(e);
    Func<object> fn = lambda.Compile(); //THIS THROWS EXCEPTION
    return Expression.Constant(fn(), type);
}

【问题讨论】:

  • 看起来像 SubSonic 中的错误。 (@Kobi:没有。)

标签: c# lambda subsonic3 linq-expressions


【解决方案1】:

在把我的头撞在墙上很多天甚至向 Jon Skeet 寻求帮助之后,我发现了问题所在。

问题实际上在于 SubSonic(@Timwi 是对的)。就在这一行:

var list = Product.Load(x => x.Active);//Active is of type bool

我改成之后:

var list = Product.Load(x => x.Active==true);

一切都很好。

【讨论】:

  • 你知道为什么会出现这个问题吗?
  • 不幸的是,这是错误消息的最高热门,因为这并不是大多数人遇到的问题的真正答案,包括我和@user1039462。对我来说,问题是您必须使用相同的 ParameterExpression everywhere。 ParameterExpression 具有相同的变量名称是不够。我相信是这样,但我会得到关于范围的异常,因为我在表达式树和根 LambdaExpression 中不是同一个 ParameterExpression 实例。
  • @Will 问题出在 SubSonic 中。如果未显式设置,则不会设置变量值。
  • @TheVillageIdiot:我知道,但是报错信息是一样的,而且这个问题是报错信息的top hit:/
  • 我只是在这里留下这条评论,因为它是错误消息的首选。如果您正在使用 ServiceStack.OrmLite 并且在尝试 Select 时遇到此异常,请注意使用 NullableVar != null 正确完成空检查,而不是 NullableVar.HasValue
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 2015-10-08
  • 1970-01-01
相关资源
最近更新 更多