如何访问匿名类型?

Tix*_*xiv 1 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)
Run Code Online (Sandbox Code Playgroud)

给我一个错误CS1061:'object'不包含'Author'的定义

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

Mar*_*ell 5

一种懒惰的方式是将"对象"切换为"动态".或者使用A Tuple泛型类型.

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

public class Testimonial {
    public string Author {get;set;}
    public string Comment {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

并使用推荐列表.

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

var arr = new[]{new{...},new{...}};
Run Code Online (Sandbox Code Playgroud)

这是你的anon类型的数组,并且;

string author = arr[0].Author;
Run Code Online (Sandbox Code Playgroud)

工作正常.