如何访问匿名类型?

时间:2010-11-13 11:47:27

标签: c# anonymous-types webmatrix

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:'object'不包含'Author'的定义

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

2 个答案:

答案 0 :(得分:5)

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

但IMO你应该只是写一个听到两个属性的类:

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

并使用推荐列表。

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

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

这是你的anon类型的数组,和;

string author = arr[0].Author;

工作正常。

答案 1 :(得分:0)

使用隐式类型数组:

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;