【问题标题】:'object' does not contain a definition for 'type'“对象”不包含“类型”的定义
【发布时间】:2013-03-29 12:56:24
【问题描述】:

我遇到了这个错误,但我不知道它是什么。我一直在寻找答案,但没有人能回答主要问题,或者我只是错过了一些东西。这是我的代码:

Connection db = new Connection();

        public ActionResult Index()
        {

            ViewBag.query = from input in db.field
                            where input.ID_FIELD == 1
                            select new {
                                type = input.FIELD_TYPE 
                            };


            return View();
        }

和视图方面

 @foreach (var item in ViewBag.query)
        { 
                @item.type//error here: 'object' does not contain a definition for 'type', why???
        }

如果我用 where 子句做一个简单的选择,就可以了 公共行动结果索引() {

            ViewBag.query = from input in db.field
                            where input.ID_FIELD == 1
                            select input.FIELD_TYPE;


            return View();
        }

我的问题可能是什么?我似乎有很多toturials也在做同样的事情,而且效果很好,就像我刚刚做的那样: int[] number = { 1, 2, 3, 4, 5 };

            var query = from num in number
                        let x = num + num + num
                        select new {avg = x};

               foreach (var item in query)
            {
                Console.WriteLine(item.avg);

            }

这里一切正常。为什么会出现问题??

【问题讨论】:

  • ViewBag.query 是FIELD_TYPE 的列表,所以item = FIELD_TYPE 并且它没有名为type 的属性。你只需要做@item,这就是你需要的价值。
  • 这行得通,但打印出来:{type = Text}。为什么?
  • 因为你没有打印出值,而是一个Type。我刚刚看到一个新的答案发布。看看 P.Brian 的回答,它将把你推向正确的方向。

标签: c# linq entity-framework asp.net-mvc-4


【解决方案1】:

您不能从方法中返回匿名类型。相反,创建一个新类型并返回该类型。

例如:

ViewBag.query = from input in db.field
                            where input.ID_FIELD == 1
                            select new MyType() {
                                someField = input.FIELD_TYPE 
                            };

public class MyType
{
  public int someField {get;set;}//compatible with whatever type FIELD_TYPE is.
}

【讨论】:

  • 它有另一种方法,而不需要创建另一个类?顺便说一句,效果很好!
  • @user2195741 - 用户无法访问编译器生成的类型。出于这个原因,我认为在返回类型时没有其他方法可以实现您的目标。然而,几乎总是有不止一种方法可以给猫剥皮,所以我不会惊讶地发现其他事情是可能的(也许是对动态的一些巧妙使用?)。这就是我在这种情况下所做的。
【解决方案2】:

在您的最后一个示例中,您没有使用“item.type”。除此之外, System.Object 不包含属性“类型”。不过,您可以使用“GetType()”。
参考here。

【讨论】:

    【解决方案3】:

    问题在于 ViewBag 是 dynamic,但您存储在其中的 匿名对象 不是,因此编译器无法直接访问其属性。您可以只在 ViewBag 属性中存储一组值,而不是整个查询:

    Connection db = new Connection();
    public ActionResult Index()
    {
    
        ViewBag.types = from input in db.field
                        where input.ID_FIELD == 1
                        select input.FIELD_TYPE;
    
        return View();
    }
    

    然后

    @foreach (var type in ViewBag.types)
    { 
        @type
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 2018-06-22
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多