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)
Gives me an error CS1061: 'object' does not contain a definition fo开发者_如何学Gor 'Author'
How do I get only the Author or Testimonial from the list of testimonials?
A lazy way would be to switch "object" for "dynamic". Or use A Tuple generic type.
But IMO you should simply write a class with hear two properties:
public class Testimonial {
public string Author {get;set;}
public string Comment {get;set;}
}
And use a List-of-Testimonial.
Another way would be to use something like:
var arr = new[]{new{...},new{...}};
This is an array of your anon-type, and;
string author = arr[0].Author;
Would work fine.
Use implicitly-typed array:
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;
精彩评论