【问题标题】:how to access anonymous type?如何访问匿名类型?
【发布时间】:2010-11-13 11:47:26
【问题描述】:
List<Object> testimonials = new List<Object>();
testimonials.Add(new {
    Author = "Author 1",
    Testimonial = "Testimonial 1"
});
testimonials.Add(new {
    Author = "Author 2",
    Testimonial = "Testimonial 2"
});
testimonials.Add(new {
    Author = "Author 3",
    Testimonial = "Testimonial 3"
});

@ObjectInfo.Print(testimonials[DateTime.Now.DayOfYear % testimonials.Count].Author)

给我一​​个错误 CS1061:“对象”不包含“作者”的定义

如何从推荐列表中仅获取作者或推荐?

【问题讨论】:

    标签: c# anonymous-types webmatrix


    【解决方案1】:

    一种懒惰的方法是将“对象”切换为“动态”。或者使用 A Tuple 泛型类型。

    但是 IMO 你应该简单地编写一个具有两个属性的类:

    public class Testimonial {
        public string Author {get;set;}
        public string Comment {get;set;}
    }
    

    并使用推荐列表。

    另一种方法是使用类似的东西:

    var arr = new[]{new{...},new{...}};
    

    这是您的匿名类型的数组,并且;

    string author = arr[0].Author;
    

    会很好。

    【讨论】:

    • +1 匿名类型非常有用,但在这种情况下,您应该定义严格类型。
    【解决方案2】:

    使用隐式类型数组:

    var arr = new[]
    {
        new { Author = "Author 1", Testimonial = "Testimonial 1" },
        new { Author = "Author 2", Testimonial = "Testimonial 2" },
        new { Author = "Author 3", Testimonial = "Testimonial 3" }
    };
    // .ToList() if needed, however array supports indexer
    
    string author = arr[i].Author;
    

    【讨论】:

      猜你喜欢
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多